🎨 Add prettier for js, less, yaml, json, ...
This commit is contained in:
1 parent
eb37b72dc1
commit
6b44909f21
159 files changed
+12772
-8543
No files matched your search
@@ -9,6 +9,7 @@ charset = utf-8
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
indent_style = space
|
||||
max_line_length = 90
|
||||
|
||||
[**.py]
|
||||
indent_size = 4
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
accessControl:
|
||||
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
|
||||
salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS
|
||||
plugins:
|
||||
virtual_printer:
|
||||
enabled: true
|
||||
tracking:
|
||||
enabled: false
|
||||
virtual_printer:
|
||||
enabled: true
|
||||
tracking:
|
||||
enabled: false
|
||||
server:
|
||||
firstRun: false
|
||||
onlineCheck:
|
||||
enabled: false
|
||||
pluginBlacklist:
|
||||
enabled: false
|
||||
secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk
|
||||
seenWizards:
|
||||
backup: null
|
||||
corewizard: 3
|
||||
tracking: null
|
||||
firstRun: false
|
||||
onlineCheck:
|
||||
enabled: false
|
||||
pluginBlacklist:
|
||||
enabled: false
|
||||
secretKey: rrdHjvmeGMPSdYWg2NGdiM7mpz9pjekk
|
||||
seenWizards:
|
||||
backup: null
|
||||
corewizard: 3
|
||||
tracking: null
|
||||
@@ -1,22 +1,22 @@
|
||||
admin:
|
||||
active: true
|
||||
apikey: null
|
||||
groups:
|
||||
active: true
|
||||
apikey: null
|
||||
groups:
|
||||
- admins
|
||||
- users
|
||||
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
|
||||
permissions: []
|
||||
roles:
|
||||
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
|
||||
permissions: []
|
||||
roles:
|
||||
- user
|
||||
- admin
|
||||
settings: {}
|
||||
settings: {}
|
||||
user:
|
||||
active: true
|
||||
apikey: null
|
||||
groups:
|
||||
active: true
|
||||
apikey: null
|
||||
groups:
|
||||
- users
|
||||
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
|
||||
permissions: []
|
||||
roles:
|
||||
password: 3033587f3b040680c77ce4fb7e8d61422878ef49a2a784227689f3b44ce66ada7f6161f8b2b037267f0d37b783a5600276eb88e1d224d24915f64e187a49a89f
|
||||
permissions: []
|
||||
roles:
|
||||
- user
|
||||
settings: {}
|
||||
settings: {}
|
||||
@@ -47,6 +47,22 @@ jobs:
|
||||
run: |
|
||||
pre-commit run --hook-stage manual black --all-files --show-diff-on-failure
|
||||
|
||||
lint-prettier:
|
||||
name: 🧹 prettier
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: 🏗 Set up Python 3.7
|
||||
uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: 3.7
|
||||
- name: 🏗 Set up dev dependencies
|
||||
run: |
|
||||
pip install -e .[develop]
|
||||
- name: 🚀 Run prettier
|
||||
run: |
|
||||
pre-commit run --hook-stage manual prettier --all-files --show-diff-on-failure
|
||||
|
||||
lint-isort:
|
||||
name: 🧹 isort
|
||||
runs-on: ubuntu-latest
|
||||
@@ -156,8 +172,8 @@ jobs:
|
||||
with:
|
||||
working-directory: tests/cypress
|
||||
browser: chrome
|
||||
start: 'octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000'
|
||||
wait-on: 'http://127.0.0.1:5000/online.txt'
|
||||
start: "octoprint -b ${{ github.workspace }}/e2econfig serve --host 127.0.0.1 --port 5000"
|
||||
wait-on: "http://127.0.0.1:5000/online.txt"
|
||||
|
||||
- name: ⬆ Upload screenshots
|
||||
uses: actions/upload-artifact@v1
|
||||
@@ -177,6 +193,7 @@ jobs:
|
||||
if: github.event_name == 'release'
|
||||
needs:
|
||||
- lint-black
|
||||
- lint-prettier
|
||||
- lint-isort
|
||||
- lint-flake8
|
||||
- test-unit
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
name: 'Lock outdated issues & PRs'
|
||||
name: "Lock outdated issues & PRs"
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 0 * * *'
|
||||
- cron: "0 0 * * *"
|
||||
|
||||
jobs:
|
||||
lock:
|
||||
@@ -12,5 +12,5 @@ jobs:
|
||||
uses: dessant/lock-threads@v2
|
||||
with:
|
||||
github-token: ${{ github.token }}
|
||||
issue-lock-comment: ''
|
||||
pr-lock-comment: ''
|
||||
issue-lock-comment: ""
|
||||
pr-lock-comment: ""
|
||||
@@ -6,7 +6,7 @@ on:
|
||||
- master
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: '0 */12 * * *'
|
||||
- cron: "0 */12 * * *"
|
||||
|
||||
jobs:
|
||||
install-branch:
|
||||
@@ -35,14 +35,14 @@ jobs:
|
||||
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
||||
uses: Ilshidur/action-discord@master
|
||||
with:
|
||||
args: '☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful'
|
||||
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` was successful"
|
||||
- name: 📧 Discord failure notification
|
||||
if: failure()
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
||||
uses: Ilshidur/action-discord@master
|
||||
with:
|
||||
args: '🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` failed'
|
||||
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ matrix.branch }}` failed"
|
||||
|
||||
install-latest:
|
||||
name: Install latest release
|
||||
@@ -69,11 +69,11 @@ jobs:
|
||||
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
||||
uses: Ilshidur/action-discord@master
|
||||
with:
|
||||
args: '☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful'
|
||||
args: "☑️ Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` was successful"
|
||||
- name: 📧 Discord failure notification
|
||||
if: failure()
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.discord_webhook }}
|
||||
uses: Ilshidur/action-discord@master
|
||||
with:
|
||||
args: '🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed'
|
||||
args: "🚫 Test install on Python ${{ matrix.python }} under `${{ matrix.os }}` for `OctoPrint/OctoPrint:${{ steps.latest.outputs.release }}` failed"
|
||||
@@ -14,5 +14,5 @@ jobs:
|
||||
with:
|
||||
token: ${{ secrets.DOCKER_ACCESS_TOKEN }}
|
||||
repository: ${{ github.repository_owner }}/octoprint-docker
|
||||
event-type: 'release'
|
||||
event-type: "release"
|
||||
client-payload: '{"tag_name": "${{ github.event.release.tag_name }}"}'
|
||||
+11
-7
@@ -11,14 +11,14 @@ repos:
|
||||
rev: main
|
||||
hooks:
|
||||
- id: codemod_dict_to_literal
|
||||
args: ['--ignore', 'src/octoprint/vendor']
|
||||
stages: ['manual']
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
stages: ["manual"]
|
||||
- id: codemod_set_to_literal
|
||||
args: ['--ignore', 'src/octoprint/vendor']
|
||||
stages: ['manual']
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
stages: ["manual"]
|
||||
- id: codemod_not_in
|
||||
args: ['--ignore', 'src/octoprint/vendor']
|
||||
stages: ['manual']
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
stages: ["manual"]
|
||||
- repo: https://github.com/pre-commit/mirrors-isort
|
||||
rev: v5.5.4
|
||||
hooks:
|
||||
@@ -27,8 +27,12 @@ repos:
|
||||
rev: stable
|
||||
hooks:
|
||||
- id: black
|
||||
args: ['--config', 'black.toml']
|
||||
args: ["--config", "black.toml"]
|
||||
- repo: https://gitlab.com/pycqa/flake8
|
||||
rev: 3.8.1
|
||||
hooks:
|
||||
- id: flake8
|
||||
- repo: https://github.com/prettier/prettier
|
||||
rev: master
|
||||
hooks:
|
||||
- id: prettier
|
||||
@@ -0,0 +1,15 @@
|
||||
src/octoprint/static/js/lib
|
||||
src/octoprint/static/vendor
|
||||
src/octoprint/static/less/bootstrap
|
||||
src/octoprint/static/less/font-awesome.less
|
||||
*.md
|
||||
*.css
|
||||
**/package.json
|
||||
**/package-lock.json
|
||||
**/*.min.js
|
||||
docs
|
||||
build
|
||||
dist
|
||||
venv
|
||||
venv2
|
||||
venv3
|
||||
@@ -0,0 +1,11 @@
|
||||
printWidth: 90
|
||||
tabWidth: 4
|
||||
semi: true
|
||||
trailingComma: "none"
|
||||
singleQuote: false
|
||||
quoteProps: consistent
|
||||
bracketSpacing: false
|
||||
overrides:
|
||||
- files: ["*.yaml", "*.yml", "*.json", "*.less"]
|
||||
options:
|
||||
tabWidth: 2
|
||||
@@ -1,6 +1,5 @@
|
||||
# OctoPrint
|
||||
|
||||
|
||||

|
||||

|
||||
[](https://pypi.python.org/pypi/octoprint/)
|
||||
@@ -8,8 +7,8 @@
|
||||
[](https://community.octoprint.org)
|
||||
[](https://discord.octoprint.org)
|
||||
[](https://twitter.com/OctoPrint3d)
|
||||
|
||||
[](https://github.com/psf/black)
|
||||
[](https://github.com/prettier/prettier)
|
||||
[](https://pycqa.github.io/isort/)
|
||||
[](https://github.com/pre-commit/pre-commit)
|
||||
|
||||
|
||||
+18
-7
@@ -4,19 +4,30 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintActionCommandNotificationClient = function(base) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var OctoPrintActionCommandNotificationClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintActionCommandNotificationClient.prototype.get = function(refresh, opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("action_command_notification"), opts);
|
||||
OctoPrintActionCommandNotificationClient.prototype.get = function (refresh, opts) {
|
||||
return this.base.get(
|
||||
this.base.getSimpleApiUrl("action_command_notification"),
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintActionCommandNotificationClient.prototype.clear = function(opts) {
|
||||
return this.base.simpleApiCommand("action_command_notification", "clear", {}, opts);
|
||||
OctoPrintActionCommandNotificationClient.prototype.clear = function (opts) {
|
||||
return this.base.simpleApiCommand(
|
||||
"action_command_notification",
|
||||
"clear",
|
||||
{},
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("action_command_notification", OctoPrintActionCommandNotificationClient);
|
||||
OctoPrintClient.registerPluginComponent(
|
||||
"action_command_notification",
|
||||
OctoPrintActionCommandNotificationClient
|
||||
);
|
||||
return OctoPrintActionCommandNotificationClient;
|
||||
});
|
||||
+30
-14
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function ActionCommandNotificationViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -8,40 +8,57 @@ $(function() {
|
||||
|
||||
self.notifications = ko.observableArray([]);
|
||||
|
||||
self.toDateTimeString = function(timestamp) {
|
||||
self.toDateTimeString = function (timestamp) {
|
||||
return formatDate(timestamp);
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)) return;
|
||||
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)
|
||||
OctoPrint.plugins.action_command_notification.get().done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.fromResponse = function (response) {
|
||||
self.notifications(response.notifications);
|
||||
};
|
||||
|
||||
self.clear = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR)) return;
|
||||
self.clear = function () {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
OctoPrint.plugins.action_command_notification.clear();
|
||||
};
|
||||
|
||||
self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
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;
|
||||
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()) {
|
||||
if (
|
||||
data.message &&
|
||||
self.settings.settings.plugins.action_command_notification.enable_popups()
|
||||
) {
|
||||
new PNotify({
|
||||
title: gettext("Printer Notification"),
|
||||
text: data.message,
|
||||
@@ -54,7 +71,6 @@ $(function() {
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
+8
-5
@@ -4,22 +4,25 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintActionCommandPromptClient = function(base) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var OctoPrintActionCommandPromptClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
|
||||
OctoPrintActionCommandPromptClient.prototype.get = function (refresh, opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
|
||||
};
|
||||
|
||||
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
|
||||
OctoPrintActionCommandPromptClient.prototype.select = function (choice, opts) {
|
||||
var data = {
|
||||
choice: choice
|
||||
};
|
||||
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
|
||||
OctoPrintClient.registerPluginComponent(
|
||||
"action_command_prompt",
|
||||
OctoPrintActionCommandPromptClient
|
||||
);
|
||||
return OctoPrintActionCommandPromptClient;
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function ActionCommandPromptViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -10,21 +10,25 @@ $(function() {
|
||||
self.text = ko.observable();
|
||||
self.buttons = ko.observableArray([]);
|
||||
|
||||
self.active = ko.pureComputed(function() {
|
||||
self.active = ko.pureComputed(function () {
|
||||
return self.text() !== undefined;
|
||||
});
|
||||
self.visible = ko.pureComputed(function() {
|
||||
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;
|
||||
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);
|
||||
OctoPrint.plugins.action_command_prompt.get().done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
self.fromResponse = function (data) {
|
||||
if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
|
||||
self.text(data.text);
|
||||
self.buttons(data.choices);
|
||||
@@ -35,7 +39,7 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.showPrompt = function() {
|
||||
self.showPrompt = function () {
|
||||
var text = self.text();
|
||||
var buttons = self.buttons();
|
||||
|
||||
@@ -44,12 +48,12 @@ $(function() {
|
||||
message: text,
|
||||
selections: buttons,
|
||||
maycancel: true, // see #3171
|
||||
onselect: function(index) {
|
||||
onselect: function (index) {
|
||||
if (index > -1) {
|
||||
self._select(index);
|
||||
}
|
||||
},
|
||||
onclose: function() {
|
||||
onclose: function () {
|
||||
self.modal(undefined);
|
||||
}
|
||||
};
|
||||
@@ -57,23 +61,28 @@ $(function() {
|
||||
self.modal(showSelectionDialog(opts));
|
||||
};
|
||||
|
||||
self._select = function(index) {
|
||||
self._select = function (index) {
|
||||
OctoPrint.plugins.action_command_prompt.select(index);
|
||||
};
|
||||
|
||||
self._closePrompt = function() {
|
||||
self._closePrompt = function () {
|
||||
var modal = self.modal();
|
||||
if (modal) {
|
||||
modal.modal("hide");
|
||||
}
|
||||
};
|
||||
|
||||
self.onStartupComplete = function() {
|
||||
self.onStartupComplete = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
|
||||
self.onDataUpdaterPluginMessage = function (plugin, data) {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT
|
||||
)
|
||||
)
|
||||
return;
|
||||
if (plugin !== "action_command_prompt") {
|
||||
return;
|
||||
}
|
||||
@@ -92,8 +101,7 @@ $(function() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function AnnouncementsViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -9,15 +9,22 @@ $(function() {
|
||||
self.channels = new ItemListHelper(
|
||||
"plugin.announcements.channels",
|
||||
{
|
||||
"channel": function (a, b) {
|
||||
channel: function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["channel"].toLocaleLowerCase() < b["channel"].toLocaleLowerCase()) return -1;
|
||||
if (a["channel"].toLocaleLowerCase() > b["channel"].toLocaleLowerCase()) return 1;
|
||||
if (
|
||||
a["channel"].toLocaleLowerCase() <
|
||||
b["channel"].toLocaleLowerCase()
|
||||
)
|
||||
return -1;
|
||||
if (
|
||||
a["channel"].toLocaleLowerCase() >
|
||||
b["channel"].toLocaleLowerCase()
|
||||
)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
{},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
@@ -32,30 +39,34 @@ $(function() {
|
||||
self.announcementDialogContent = undefined;
|
||||
self.announcementDialogTabs = undefined;
|
||||
|
||||
self.setupTabLink = function(item) {
|
||||
self.setupTabLink = function (item) {
|
||||
$("a[data-toggle='tab']", item).on("show", self.resetContentScroll);
|
||||
};
|
||||
|
||||
self.resetContentScroll = function() {
|
||||
self.resetContentScroll = function () {
|
||||
self.announcementDialogContent.scrollTop(0);
|
||||
};
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
self.toggleButtonCss = function (data) {
|
||||
var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off";
|
||||
var disabled = (self.enableToggle(data)) ? "" : " disabled";
|
||||
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.toggleButtonTitle = function (data) {
|
||||
return data.forced
|
||||
? gettext("Cannot be toggled")
|
||||
: data.enabled
|
||||
? gettext("Disable Channel")
|
||||
: gettext("Enable Channel");
|
||||
};
|
||||
|
||||
self.enableToggle = function(data) {
|
||||
self.enableToggle = function (data) {
|
||||
return !data.forced;
|
||||
};
|
||||
|
||||
self.cleanedLink = function(data) {
|
||||
self.cleanedLink = function (data) {
|
||||
// Strips any query parameters from the link and returns it
|
||||
var link = data.link;
|
||||
if (!link) return link;
|
||||
@@ -67,8 +78,13 @@ $(function() {
|
||||
return link;
|
||||
};
|
||||
|
||||
self.markRead = function(channel, until, reload) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
self.markRead = function (channel, until, reload) {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
reload = !!reload;
|
||||
|
||||
@@ -85,16 +101,21 @@ $(function() {
|
||||
dataType: "json",
|
||||
data: JSON.stringify(payload),
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
success: function() {
|
||||
success: function () {
|
||||
if (reload) {
|
||||
self.retrieveData()
|
||||
self.retrieveData();
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
self.toggleChannel = function(channel) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE)) return;
|
||||
self.toggleChannel = function (channel) {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
|
||||
|
||||
@@ -108,18 +129,23 @@ $(function() {
|
||||
dataType: "json",
|
||||
data: JSON.stringify(payload),
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
success: function() {
|
||||
self.retrieveData()
|
||||
success: function () {
|
||||
self.retrieveData();
|
||||
}
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
self.refreshAnnouncements = function() {
|
||||
self.refreshAnnouncements = function () {
|
||||
self.retrieveData(true);
|
||||
};
|
||||
|
||||
self.retrieveData = function(force) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
self.retrieveData = function (force) {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
var url = PLUGIN_BASEURL + "announcements/channels";
|
||||
if (force) {
|
||||
@@ -130,20 +156,25 @@ $(function() {
|
||||
url: url,
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: function(data) {
|
||||
success: function (data) {
|
||||
self.fromResponse(data);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
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 = [];
|
||||
_.each(data.channels, function(value) {
|
||||
_.each(data.channels, function (value) {
|
||||
value.last = value.data.length ? value.data[0].published : undefined;
|
||||
value.count = value.data.length;
|
||||
unread += value.unread;
|
||||
@@ -157,8 +188,13 @@ $(function() {
|
||||
self.selectTab(currentTab);
|
||||
};
|
||||
|
||||
self.showAnnouncementDialog = function(channel) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
self.showAnnouncementDialog = function (channel) {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
// lazy load images that still need lazy-loading
|
||||
$("#plugin_announcements_dialog_content article img").lazyload();
|
||||
@@ -166,12 +202,18 @@ $(function() {
|
||||
self.announcementDialogContent.scrollTop(0);
|
||||
|
||||
if (!self.announcementDialog.hasClass("in")) {
|
||||
self.announcementDialog.modal({
|
||||
minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
|
||||
}).css({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
self.announcementDialog
|
||||
.modal({
|
||||
minHeight: function () {
|
||||
return Math.max($.fn.modal.defaults.maxHeight() - 80, 250);
|
||||
}
|
||||
})
|
||||
.css({
|
||||
"width": "auto",
|
||||
"margin-left": function () {
|
||||
return -($(this).width() / 2);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var tab = undefined;
|
||||
@@ -183,24 +225,29 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.selectTab = function(tab) {
|
||||
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");
|
||||
$("a:first", self.announcementDialogTabs).tab("show");
|
||||
}
|
||||
};
|
||||
|
||||
self.displayAnnouncements = function(channels) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
|
||||
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) {
|
||||
var cutAfterNewline = function (text) {
|
||||
text = text.trim();
|
||||
|
||||
var firstNewlinePos = text.indexOf("\n");
|
||||
@@ -211,7 +258,7 @@ $(function() {
|
||||
return text;
|
||||
};
|
||||
|
||||
var stripParagraphs = function(text) {
|
||||
var stripParagraphs = function (text) {
|
||||
if (_.startsWith(text, "<p>")) {
|
||||
text = text.substr("<p>".length);
|
||||
}
|
||||
@@ -219,10 +266,10 @@ $(function() {
|
||||
text = text.substr(0, text.length - "</p>".length);
|
||||
}
|
||||
|
||||
return text.replace(/<\/p>\s*<p>/ig, "<br>");
|
||||
return text.replace(/<\/p>\s*<p>/gi, "<br>");
|
||||
};
|
||||
|
||||
_.each(channels, function(value) {
|
||||
_.each(channels, function (value) {
|
||||
var key = value.key;
|
||||
var channel = value.channel;
|
||||
var priority = value.priority;
|
||||
@@ -233,7 +280,9 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
var newItems = _.filter(items, function(entry) { return !entry.read; });
|
||||
var newItems = _.filter(items, function (entry) {
|
||||
return !entry.read;
|
||||
});
|
||||
if (newItems.length == 0) {
|
||||
// no new items at all, we don't display anything for this channel
|
||||
return;
|
||||
@@ -248,23 +297,48 @@ $(function() {
|
||||
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());
|
||||
_.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 = 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 +=
|
||||
"<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 +=
|
||||
"<p>" +
|
||||
gettext(_.sprintf("... and %(rest)d more.", {rest: rest})) +
|
||||
"</p>";
|
||||
}
|
||||
|
||||
text += "<small>" + gettext("You can edit your announcement subscriptions under Settings > Announcements.") + "</small>";
|
||||
text +=
|
||||
"<small>" +
|
||||
gettext(
|
||||
"You can edit your announcement subscriptions under Settings > Announcements."
|
||||
) +
|
||||
"</small>";
|
||||
|
||||
var options = {
|
||||
title: channel,
|
||||
@@ -272,27 +346,31 @@ $(function() {
|
||||
hide: false,
|
||||
confirm: {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Later"),
|
||||
click: function(notice) {
|
||||
notice.remove();
|
||||
self.hiddenChannels.push(key);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}, {
|
||||
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,
|
||||
@@ -311,41 +389,48 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.hideAnnouncements = function() {
|
||||
_.each(self.channelNotifications, function(notification, key) {
|
||||
self.hideAnnouncements = function () {
|
||||
_.each(self.channelNotifications, function (notification, key) {
|
||||
notification.remove();
|
||||
});
|
||||
self.channelNotifications = {};
|
||||
};
|
||||
|
||||
self.configureAnnouncements = function() {
|
||||
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.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.onStartup = function () {
|
||||
self.announcementDialog = $("#plugin_announcements_dialog");
|
||||
self.announcementDialogContent = $("#plugin_announcements_dialog_content");
|
||||
self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs");
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function(payload) {
|
||||
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"]
|
||||
elements: [
|
||||
"#plugin_announcements_dialog",
|
||||
"#settings_plugin_announcements",
|
||||
"#navbar_plugin_announcements"
|
||||
]
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
table {
|
||||
th, td {
|
||||
th,
|
||||
td {
|
||||
&.settings_plugin_announcements_channels_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
|
||||
@@ -4,59 +4,80 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintAppKeysClient = function(base) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var OctoPrintAppKeysClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.getKeys = function(opts) {
|
||||
OctoPrintAppKeysClient.prototype.getKeys = function (opts) {
|
||||
return this.base.simpleApiGet("appkeys", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) {
|
||||
return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts);
|
||||
OctoPrintAppKeysClient.prototype.getAllKeys = function (opts) {
|
||||
return this.base.get(
|
||||
OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true",
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts);
|
||||
OctoPrintAppKeysClient.prototype.generateKey = function (app, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "generate", {app: app}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.generateKeyForUser = function(user, app, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "generate", {"app": app, "user": user}, opts);
|
||||
OctoPrintAppKeysClient.prototype.generateKeyForUser = function (user, app, opts) {
|
||||
return this.base.simpleApiCommand(
|
||||
"appkeys",
|
||||
"generate",
|
||||
{app: app, user: user},
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts);
|
||||
OctoPrintAppKeysClient.prototype.revokeKey = function (key, opts) {
|
||||
return this.base.simpleApiCommand("appkeys", "revoke", {key: key}, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) {
|
||||
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts);
|
||||
OctoPrintAppKeysClient.prototype.decide = function (token, decision, opts) {
|
||||
return this.base.postJson(
|
||||
this.base.getBlueprintUrl("appkeys") + "decision/" + token,
|
||||
{decision: !!decision},
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.probe = function(opts) {
|
||||
OctoPrintAppKeysClient.prototype.probe = function (opts) {
|
||||
return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.request = function(app, opts) {
|
||||
OctoPrintAppKeysClient.prototype.request = function (app, opts) {
|
||||
return this.requestForUser(app, undefined, opts);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) {
|
||||
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts);
|
||||
OctoPrintAppKeysClient.prototype.requestForUser = function (app, user, opts) {
|
||||
return this.base.postJson(
|
||||
this.base.getBlueprintUrl("appkeys") + "request",
|
||||
{app: app, user: user},
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) {
|
||||
return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts);
|
||||
OctoPrintAppKeysClient.prototype.checkDecision = function (token, opts) {
|
||||
return this.base.get(
|
||||
this.base.getBlueprintUrl("appkeys") + "request/" + token,
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintAppKeysClient.prototype.authenticate = function(app, user) {
|
||||
OctoPrintAppKeysClient.prototype.authenticate = function (app, user) {
|
||||
var deferred = $.Deferred();
|
||||
var client = this;
|
||||
|
||||
client.probe()
|
||||
.done(function() {
|
||||
client.requestForUser(app, user)
|
||||
.done(function(response) {
|
||||
client
|
||||
.probe()
|
||||
.done(function () {
|
||||
client
|
||||
.requestForUser(app, user)
|
||||
.done(function (response) {
|
||||
var token = response.app_token;
|
||||
if (!token) {
|
||||
// no token received, something went wrong
|
||||
@@ -65,9 +86,10 @@
|
||||
}
|
||||
|
||||
var interval = 1000;
|
||||
var poll = function() {
|
||||
client.checkDecision(token)
|
||||
.done(function(response) {
|
||||
var poll = function () {
|
||||
client
|
||||
.checkDecision(token)
|
||||
.done(function (response) {
|
||||
if (response.api_key) {
|
||||
// got a decision, resolve the promise
|
||||
deferred.resolve(response.api_key);
|
||||
@@ -77,19 +99,19 @@
|
||||
window.setTimeout(poll, interval);
|
||||
}
|
||||
})
|
||||
.fail(function() {
|
||||
.fail(function () {
|
||||
// something went wrong
|
||||
deferred.reject();
|
||||
});
|
||||
};
|
||||
window.setTimeout(poll, interval);
|
||||
})
|
||||
.fail(function() {
|
||||
.fail(function () {
|
||||
// something went wrong
|
||||
deferred.reject();
|
||||
});
|
||||
})
|
||||
.fail(function() {
|
||||
.fail(function () {
|
||||
// workflow unsupported
|
||||
deferred.reject();
|
||||
});
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function AppKeysDialogViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.dialog = undefined;
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onStartup = function () {
|
||||
self.dialog = $("#plugin_appkeys_keygenerated");
|
||||
};
|
||||
|
||||
self.showDialog = function(title, data) {
|
||||
self.showDialog = function (title, data) {
|
||||
if (self.dialog === undefined) return;
|
||||
|
||||
var qrcode = {
|
||||
@@ -27,17 +27,19 @@ $(function() {
|
||||
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")
|
||||
self.dialog
|
||||
.find("#plugin_appkeys_keygenerated_key_copy")
|
||||
.off()
|
||||
.click(function() {
|
||||
.click(function () {
|
||||
copyToClipboard(data.api_key);
|
||||
});
|
||||
self.dialog.find("#plugin_appkeys_keygenerated_key_qrcode")
|
||||
self.dialog
|
||||
.find("#plugin_appkeys_keygenerated_key_qrcode")
|
||||
.empty()
|
||||
.qrcode(qrcode);
|
||||
|
||||
self.dialog.modal("show");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function UserAppKeysViewModel(parameters) {
|
||||
@@ -48,15 +50,14 @@ $(function() {
|
||||
self.keys = new ItemListHelper(
|
||||
"plugin.appkeys.userkeys",
|
||||
{
|
||||
"app": function (a, b) {
|
||||
app: function (a, b) {
|
||||
// sorts ascending
|
||||
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",
|
||||
[],
|
||||
[],
|
||||
@@ -67,51 +68,62 @@ $(function() {
|
||||
|
||||
self.editorApp = ko.observable();
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.appkeys.getKeys()
|
||||
.done(self.fromResponse);
|
||||
self.requestData = function () {
|
||||
OctoPrint.plugins.appkeys.getKeys().done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.fromResponse = function (response) {
|
||||
self.keys.updateItems(response.keys);
|
||||
self.pending = response.pending;
|
||||
_.each(self.pending, function(data, token) {
|
||||
_.each(self.pending, function (data, token) {
|
||||
self.openRequests[token] = self.promptForAccess(data.app_id, token);
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
self.generateKey = function() {
|
||||
return OctoPrint.plugins.appkeys.generateKey(self.editorApp())
|
||||
self.generateKey = function () {
|
||||
return OctoPrint.plugins.appkeys
|
||||
.generateKey(self.editorApp())
|
||||
.done(self.requestData)
|
||||
.done(function() {
|
||||
.done(function () {
|
||||
self.editorApp("");
|
||||
});
|
||||
};
|
||||
|
||||
self.revokeKey = function(key) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(self.requestData);
|
||||
self.revokeKey = function (key) {
|
||||
var perform = function () {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key).done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
|
||||
perform);
|
||||
showConfirmationDialog(
|
||||
_.sprintf(
|
||||
gettext('You are about to revoke the application key "%(key)s".'),
|
||||
{key: _.escape(key)}
|
||||
),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.allowApp = function(token) {
|
||||
return OctoPrint.plugins.appkeys.decide(token, true)
|
||||
.done(self.requestData);
|
||||
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.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.");
|
||||
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>";
|
||||
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,
|
||||
@@ -119,19 +131,22 @@ $(function() {
|
||||
icon: "fa fa-key",
|
||||
confirm: {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Allow"),
|
||||
click: function(notice) {
|
||||
self.allowApp(token);
|
||||
notice.remove();
|
||||
buttons: [
|
||||
{
|
||||
text: gettext("Allow"),
|
||||
click: function (notice) {
|
||||
self.allowApp(token);
|
||||
notice.remove();
|
||||
}
|
||||
},
|
||||
{
|
||||
text: gettext("Deny"),
|
||||
click: function (notice) {
|
||||
self.denyApp(token);
|
||||
notice.remove();
|
||||
}
|
||||
}
|
||||
}, {
|
||||
text: gettext("Deny"),
|
||||
click: function(notice) {
|
||||
self.denyApp(token);
|
||||
notice.remove();
|
||||
}
|
||||
}]
|
||||
]
|
||||
},
|
||||
buttons: {
|
||||
sticker: false,
|
||||
@@ -140,15 +155,15 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.onUserSettingsShown = function() {
|
||||
self.onUserSettingsShown = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.onUserLoggedIn = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
self.onDataUpdaterPluginMessage = function (plugin, data) {
|
||||
if (plugin !== "appkeys") {
|
||||
return;
|
||||
}
|
||||
@@ -169,7 +184,6 @@ $(function() {
|
||||
}
|
||||
|
||||
self.openRequests[token] = self.promptForAccess(app, token);
|
||||
|
||||
} else if (data.type === "end_request") {
|
||||
token = data.user_token;
|
||||
|
||||
@@ -178,7 +192,7 @@ $(function() {
|
||||
if (self.openRequests[token].state !== "closed") {
|
||||
self.openRequests[token].remove();
|
||||
}
|
||||
delete self.openRequests[token]
|
||||
delete self.openRequests[token];
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -193,7 +207,7 @@ $(function() {
|
||||
self.keys = new ItemListHelper(
|
||||
"plugin.appkeys.allkeys",
|
||||
{
|
||||
"user_app": function (a, b) {
|
||||
user_app: function (a, b) {
|
||||
// sorts ascending, first by user, then by app
|
||||
if (a["user_id"] > b["user_id"]) return 1;
|
||||
if (a["user_id"] < b["user_id"]) return -1;
|
||||
@@ -204,8 +218,7 @@ $(function() {
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
{},
|
||||
"user_app",
|
||||
[],
|
||||
[],
|
||||
@@ -219,29 +232,28 @@ $(function() {
|
||||
|
||||
self.markedForDeletion = ko.observableArray([]);
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.onSettingsShown = function () {
|
||||
self.requestData();
|
||||
self.editorUser(self.loginState.username());
|
||||
self.editorApp("");
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.onUserLoggedIn = function () {
|
||||
self.requestData();
|
||||
self.editorUser(self.loginState.username());
|
||||
self.editorApp("");
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.appkeys.getAllKeys()
|
||||
.done(self.fromResponse);
|
||||
self.requestData = function () {
|
||||
OctoPrint.plugins.appkeys.getAllKeys().done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.fromResponse = function (response) {
|
||||
self.keys.updateItems(response.keys);
|
||||
|
||||
var users = [];
|
||||
var apps = [];
|
||||
_.each(response.keys, function(key) {
|
||||
_.each(response.keys, function (key) {
|
||||
users.push(key.user_id);
|
||||
apps.push(key.app_id.toLowerCase());
|
||||
});
|
||||
@@ -255,77 +267,116 @@ $(function() {
|
||||
self.apps(apps);
|
||||
};
|
||||
|
||||
self.generateKey = function() {
|
||||
return OctoPrint.plugins.appkeys.generateKeyForUser(self.editorUser(), self.editorApp())
|
||||
self.generateKey = function () {
|
||||
return OctoPrint.plugins.appkeys
|
||||
.generateKeyForUser(self.editorUser(), self.editorApp())
|
||||
.done(self.requestData)
|
||||
.done(function() {
|
||||
.done(function () {
|
||||
self.editorUser(self.loginState.username());
|
||||
self.editorApp("");
|
||||
})
|
||||
.done(function(data) {
|
||||
.done(function (data) {
|
||||
self.dialog.showDialog(gettext("New key generated!"), data);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
self.revokeKey = function(key) {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(self.requestData);
|
||||
self.revokeKey = function (key) {
|
||||
var perform = function () {
|
||||
OctoPrint.plugins.appkeys.revokeKey(key).done(self.requestData);
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
|
||||
perform);
|
||||
showConfirmationDialog(
|
||||
_.sprintf(
|
||||
gettext('You are about to revoke the application key "%(key)s".'),
|
||||
{key: _.escape(key)}
|
||||
),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.revokeMarked = function() {
|
||||
var perform = function() {
|
||||
self._bulkRevoke(self.markedForDeletion())
|
||||
.done(function() {
|
||||
self.markedForDeletion.removeAll();
|
||||
});
|
||||
self.revokeMarked = function () {
|
||||
var perform = function () {
|
||||
self._bulkRevoke(self.markedForDeletion()).done(function () {
|
||||
self.markedForDeletion.removeAll();
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}),
|
||||
perform);
|
||||
showConfirmationDialog(
|
||||
_.sprintf(
|
||||
gettext("You are about to revoke %(count)d application keys."),
|
||||
{count: self.markedForDeletion().length}
|
||||
),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.markAllOnPageForDeletion = function() {
|
||||
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key"))));
|
||||
self.markAllOnPageForDeletion = function () {
|
||||
self.markedForDeletion(
|
||||
_.uniq(
|
||||
self
|
||||
.markedForDeletion()
|
||||
.concat(_.map(self.keys.paginatedItems(), "api_key"))
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
self.markAllForDeletion = function() {
|
||||
self.markAllForDeletion = function () {
|
||||
self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key")));
|
||||
};
|
||||
|
||||
self.markAllByUserForDeletion = function(user) {
|
||||
self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); });
|
||||
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.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), "api_key"))));
|
||||
self.markAllByFilterForDeletion = function (filter) {
|
||||
self.markedForDeletion(
|
||||
_.uniq(
|
||||
self
|
||||
.markedForDeletion()
|
||||
.concat(_.map(_.filter(self.keys.allItems, filter), "api_key"))
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
self.clearMarked = function() {
|
||||
self.clearMarked = function () {
|
||||
self.markedForDeletion.removeAll();
|
||||
};
|
||||
|
||||
self._bulkRevoke = function(keys) {
|
||||
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(key) {
|
||||
return OctoPrint.plugins.appkeys.revokeKey(key)
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: _.escape(key)}), true);
|
||||
message = _.sprintf(gettext("Revoking %(count)d application keys..."), {
|
||||
count: keys.length
|
||||
});
|
||||
handler = function (key) {
|
||||
return OctoPrint.plugins.appkeys
|
||||
.revokeKey(key)
|
||||
.done(function () {
|
||||
deferred.notify(
|
||||
_.sprintf(gettext("Revoked %(key)s..."), {
|
||||
key: _.escape(key)
|
||||
}),
|
||||
true
|
||||
);
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: _.escape(key)});
|
||||
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: _.escape(key), error: _.escape(jqXHR.responseText)});
|
||||
.fail(function (jqXHR) {
|
||||
var short = _.sprintf(
|
||||
gettext("Revocation of %(key)s failed, continuing..."),
|
||||
{key: _.escape(key)}
|
||||
);
|
||||
var long = _.sprintf(
|
||||
gettext("Deletion of %(key)s failed: %(error)s"),
|
||||
{key: _.escape(key), error: _.escape(jqXHR.responseText)}
|
||||
);
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
};
|
||||
@@ -343,25 +394,20 @@ $(function() {
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(keys, function(key) {
|
||||
_.each(keys, function (key) {
|
||||
var request = handler(key);
|
||||
requests.push(request)
|
||||
requests.push(request);
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
AppKeysDialogViewModel,
|
||||
[],
|
||||
[]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push([AppKeysDialogViewModel, [], []]);
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
UserAppKeysViewModel,
|
||||
@@ -373,5 +419,5 @@ $(function() {
|
||||
AllAppKeysViewModel,
|
||||
["appKeysDialogViewModel", "loginStateViewModel", "accessViewModel"],
|
||||
["#settings_plugin_appkeys"]
|
||||
])
|
||||
]);
|
||||
});
|
||||
@@ -4,17 +4,17 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintBackupClient = function(base) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var OctoPrintBackupClient = function (base) {
|
||||
this.base = base;
|
||||
this.url = this.base.getBlueprintUrl("backup");
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.get = function(refresh, opts) {
|
||||
OctoPrintBackupClient.prototype.get = function (refresh, opts) {
|
||||
return this.base.get(this.url, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) {
|
||||
OctoPrintBackupClient.prototype.createBackup = function (exclude, opts) {
|
||||
exclude = exclude || [];
|
||||
|
||||
var data = {
|
||||
@@ -24,11 +24,11 @@
|
||||
return this.base.postJson(this.url + "backup", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) {
|
||||
OctoPrintBackupClient.prototype.deleteBackup = function (backup, opts) {
|
||||
return this.base.delete(this.url + "backup/" + backup, opts);
|
||||
};
|
||||
|
||||
OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) {
|
||||
OctoPrintBackupClient.prototype.restoreBackup = function (backup, opts) {
|
||||
var data = {
|
||||
path: backup
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function BackupViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -8,15 +8,14 @@ $(function() {
|
||||
self.backups = new ItemListHelper(
|
||||
"plugin.backup.backups",
|
||||
{
|
||||
"date": function (a, b) {
|
||||
date: function (a, b) {
|
||||
// sorts descending
|
||||
if (a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
{},
|
||||
"date",
|
||||
[],
|
||||
[],
|
||||
@@ -37,7 +36,7 @@ $(function() {
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function(e, data) {
|
||||
add: function (e, data) {
|
||||
if (data.files.length === 0) {
|
||||
// no files? ignore
|
||||
return false;
|
||||
@@ -46,7 +45,7 @@ $(function() {
|
||||
self.backupUploadName(data.files[0].name);
|
||||
self.backupUploadData = data;
|
||||
},
|
||||
done: function(e, data) {
|
||||
done: function (e, data) {
|
||||
self.backupUploadName(undefined);
|
||||
self.backupUploadData = undefined;
|
||||
}
|
||||
@@ -63,113 +62,151 @@ $(function() {
|
||||
|
||||
self.loglines = ko.observableArray([]);
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.plugins.backup.get()
|
||||
.done(self.fromResponse);
|
||||
self.requestData = function () {
|
||||
OctoPrint.plugins.backup.get().done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.fromResponse = function (response) {
|
||||
self.backups.updateItems(response.backups);
|
||||
self.unknownPlugins(response.unknown_plugins);
|
||||
self.restoreSupported(response.restore_supported);
|
||||
};
|
||||
|
||||
self.createBackup = function() {
|
||||
self.createBackup = function () {
|
||||
var excluded = self.excludeFromBackup();
|
||||
OctoPrint.plugins.backup.createBackup(excluded)
|
||||
.done(function() {
|
||||
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();
|
||||
});
|
||||
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);
|
||||
showConfirmationDialog(
|
||||
_.sprintf(gettext('You are about to delete backup file "%(name)s".'), {
|
||||
name: _.escape(backup)
|
||||
}),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.restoreBackup = function(backup) {
|
||||
self.restoreBackup = function (backup) {
|
||||
if (!self.restoreSupported()) return;
|
||||
|
||||
var perform = function() {
|
||||
var perform = function () {
|
||||
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});
|
||||
self.restoreDialog.modal({
|
||||
keyboard: false,
|
||||
backdrop: "static",
|
||||
show: true
|
||||
});
|
||||
|
||||
OctoPrint.plugins.backup.restoreBackup(backup);
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(backup)}),
|
||||
perform);
|
||||
showConfirmationDialog(
|
||||
_.sprintf(
|
||||
gettext(
|
||||
'You are about to restore the backup file "%(name)s". This cannot be undone.'
|
||||
),
|
||||
{name: _.escape(backup)}
|
||||
),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.performRestoreFromUpload = function() {
|
||||
self.performRestoreFromUpload = function () {
|
||||
if (self.backupUploadData === undefined) return;
|
||||
|
||||
var perform = function() {
|
||||
var perform = function () {
|
||||
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: "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.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())}),
|
||||
perform);
|
||||
showConfirmationDialog(
|
||||
_.sprintf(
|
||||
gettext(
|
||||
'You are about to upload and restore the backup file "%(name)s". This cannot be undone.'
|
||||
),
|
||||
{name: _.escape(self.backupUploadName())}
|
||||
),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.deleteUnknownPluginRecord = function() {
|
||||
var perform = function() {
|
||||
OctoPrint.plugins.backup.deleteUnknownPlugins()
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
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);
|
||||
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.markFilesOnPage = function () {
|
||||
self.markedForBackupDeletion(
|
||||
_.uniq(
|
||||
self
|
||||
.markedForBackupDeletion()
|
||||
.concat(_.map(self.backups.paginatedItems(), "name"))
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
self.markAllFiles = function() {
|
||||
self.markAllFiles = function () {
|
||||
self.markedForBackupDeletion(_.map(self.backups.allItems, "name"));
|
||||
};
|
||||
|
||||
self.clearMarkedFiles = function() {
|
||||
self.clearMarkedFiles = function () {
|
||||
self.markedForBackupDeletion.removeAll();
|
||||
};
|
||||
|
||||
self.removeMarkedFiles = function() {
|
||||
var perform = function() {
|
||||
self._bulkRemove(self.markedForBackupDeletion())
|
||||
.done(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);
|
||||
showConfirmationDialog(
|
||||
_.sprintf(gettext("You are about to delete %(count)d backups."), {
|
||||
count: self.markedForBackupDeletion().length
|
||||
}),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onStartup = function () {
|
||||
self.restoreDialog = $("#settings_plugin_backup_restoredialog");
|
||||
self.restoreOutput = $("#settings_plugin_backup_restoredialog_output");
|
||||
};
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.onSettingsShown = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
self.onDataUpdaterPluginMessage = function (plugin, data) {
|
||||
if (plugin !== "backup") return;
|
||||
|
||||
if (data.type === "backup_done") {
|
||||
@@ -186,74 +223,131 @@ $(function() {
|
||||
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)}),
|
||||
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: 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.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.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)}),
|
||||
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)}),
|
||||
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: _.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.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._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) {
|
||||
self._preprocessLine = function (line) {
|
||||
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
|
||||
line.stream = "stdout";
|
||||
}
|
||||
return line;
|
||||
};
|
||||
|
||||
self._bulkRemove = function(files) {
|
||||
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);
|
||||
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)});
|
||||
.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);
|
||||
});
|
||||
};
|
||||
@@ -271,15 +365,14 @@ $(function() {
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(files, function(filename) {
|
||||
_.each(files, function (filename) {
|
||||
var request = handler(filename);
|
||||
requests.push(request)
|
||||
requests.push(request);
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function CoreWizardAclViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -13,84 +13,97 @@ $(function() {
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.passwordMismatch = ko.pureComputed(function() {
|
||||
self.passwordMismatch = ko.pureComputed(function () {
|
||||
return self.password() != self.confirmedPassword();
|
||||
});
|
||||
|
||||
self.validUsername = ko.pureComputed(function() {
|
||||
self.validUsername = ko.pureComputed(function () {
|
||||
return self.username() && self.username().trim() != "";
|
||||
});
|
||||
|
||||
self.validPassword = ko.pureComputed(function() {
|
||||
self.validPassword = ko.pureComputed(function () {
|
||||
return self.password() && self.password().trim() != "";
|
||||
});
|
||||
|
||||
self.validData = ko.pureComputed(function() {
|
||||
return !self.passwordMismatch() && self.validUsername() && self.validPassword();
|
||||
self.validData = ko.pureComputed(function () {
|
||||
return (
|
||||
!self.passwordMismatch() && self.validUsername() && self.validPassword()
|
||||
);
|
||||
});
|
||||
|
||||
self.keepAccessControl = function() {
|
||||
self.keepAccessControl = function () {
|
||||
if (!self.validData()) return;
|
||||
|
||||
var data = {
|
||||
"ac": true,
|
||||
"user": self.username(),
|
||||
"pass1": self.password(),
|
||||
"pass2": self.confirmedPassword()
|
||||
ac: true,
|
||||
user: self.username(),
|
||||
pass1: self.password(),
|
||||
pass2: self.confirmedPassword()
|
||||
};
|
||||
self._sendData(data);
|
||||
};
|
||||
|
||||
self.disableAccessControl = function() {
|
||||
var message = gettext("If you disable Access Control <strong>and</strong> your OctoPrint installation is accessible from the internet, your printer <strong>will be accessible by everyone - that also includes the bad guys!</strong>");
|
||||
self.disableAccessControl = function () {
|
||||
var message = gettext(
|
||||
"If you disable Access Control <strong>and</strong> your OctoPrint installation is accessible from the internet, your printer <strong>will be accessible by everyone - that also includes the bad guys!</strong>"
|
||||
);
|
||||
showConfirmationDialog({
|
||||
message: message,
|
||||
onproceed: function (e) {
|
||||
var data = {
|
||||
"ac": false
|
||||
ac: false
|
||||
};
|
||||
self._sendData(data);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self._sendData = function(data, callback) {
|
||||
OctoPrint.postJson("plugin/corewizard/acl", data)
|
||||
.done(function() {
|
||||
self.setup(true);
|
||||
self.decision(data.ac);
|
||||
if (data.ac) {
|
||||
// we now log the user in
|
||||
var user = data.user;
|
||||
var pass = data.pass1;
|
||||
self.loginStateViewModel.login(user, pass, true)
|
||||
.done(function() {
|
||||
if (callback) callback();
|
||||
});
|
||||
} else {
|
||||
self._sendData = function (data, callback) {
|
||||
OctoPrint.postJson("plugin/corewizard/acl", data).done(function () {
|
||||
self.setup(true);
|
||||
self.decision(data.ac);
|
||||
if (data.ac) {
|
||||
// we now log the user in
|
||||
var user = data.user;
|
||||
var pass = data.pass1;
|
||||
self.loginStateViewModel.login(user, pass, true).done(function () {
|
||||
if (callback) callback();
|
||||
}
|
||||
});
|
||||
});
|
||||
} else {
|
||||
if (callback) callback();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
self.onBeforeWizardTabChange = function (next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
|
||||
if (
|
||||
!current ||
|
||||
!_.startsWith(current, "wizard_plugin_corewizard_acl_") ||
|
||||
self.setup()
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
showMessageDialog({
|
||||
title: gettext("Please set up Access Control"),
|
||||
message: gettext("You haven't yet set up access control. You need to either setup a username and password and click \"Keep Access Control Enabled\" or click \"Disable Access Control\" before continuing")
|
||||
message: gettext(
|
||||
'You haven\'t yet set up access control. You need to either setup a username and password and click "Keep Access Control Enabled" or click "Disable Access Control" before continuing'
|
||||
)
|
||||
});
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.acl && response.corewizard.details.acl.required;
|
||||
self.onWizardDetails = function (response) {
|
||||
self.required =
|
||||
response &&
|
||||
response.corewizard &&
|
||||
response.corewizard.details &&
|
||||
response.corewizard.details.acl &&
|
||||
response.corewizard.details.acl.required;
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
self.onWizardFinish = function () {
|
||||
if (!self.required) return;
|
||||
|
||||
if (!self.decision()) {
|
||||
@@ -106,17 +119,25 @@ $(function() {
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.webcam && response.corewizard.details.webcam.required;
|
||||
self.onWizardDetails = function (response) {
|
||||
self.required =
|
||||
response &&
|
||||
response.corewizard &&
|
||||
response.corewizard.details &&
|
||||
response.corewizard.details.webcam &&
|
||||
response.corewizard.details.webcam.required;
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
self.onWizardFinish = function () {
|
||||
if (!self.required) return;
|
||||
if (self.settingsViewModel.webcam_streamUrl()
|
||||
|| (self.settingsViewModel.webcam_snapshotUrl() && self.settingsViewModel.webcam_ffmpegPath())) {
|
||||
if (
|
||||
self.settingsViewModel.webcam_streamUrl() ||
|
||||
(self.settingsViewModel.webcam_snapshotUrl() &&
|
||||
self.settingsViewModel.webcam_ffmpegPath())
|
||||
) {
|
||||
return "reload";
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function CoreWizardServerCommandsViewModel(parameters) {
|
||||
@@ -136,22 +157,26 @@ $(function() {
|
||||
self.required = false;
|
||||
self.active = false;
|
||||
|
||||
self.enableOnlineCheck = function() {
|
||||
self.enableOnlineCheck = function () {
|
||||
self.settingsViewModel.server_onlineCheck_enabled(true);
|
||||
self.decision(true);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.disableOnlineCheck = function() {
|
||||
self.disableOnlineCheck = function () {
|
||||
self.settingsViewModel.server_onlineCheck_enabled(false);
|
||||
self.decision(false);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
self.onBeforeWizardTabChange = function (next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") || self.setup()) {
|
||||
if (
|
||||
!current ||
|
||||
!_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") ||
|
||||
self.setup()
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -159,7 +184,7 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onBeforeWizardFinish = function() {
|
||||
self.onBeforeWizardFinish = function () {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (self.setup()) {
|
||||
@@ -170,18 +195,25 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required;
|
||||
self.onWizardDetails = function (response) {
|
||||
self.required =
|
||||
response &&
|
||||
response.corewizard &&
|
||||
response.corewizard.details &&
|
||||
response.corewizard.details.onlinecheck &&
|
||||
response.corewizard.details.onlinecheck.required;
|
||||
};
|
||||
|
||||
self._showDecisionNeededDialog = function() {
|
||||
self._showDecisionNeededDialog = function () {
|
||||
showMessageDialog({
|
||||
title: gettext("Please set up the online connectivity check"),
|
||||
message: gettext("You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing.")
|
||||
message: gettext(
|
||||
"You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing."
|
||||
)
|
||||
});
|
||||
};
|
||||
|
||||
self._sendData = function() {
|
||||
self._sendData = function () {
|
||||
var data = {
|
||||
server: {
|
||||
onlineCheck: {
|
||||
@@ -194,13 +226,11 @@ $(function() {
|
||||
};
|
||||
|
||||
self.active = true;
|
||||
self.settingsViewModel.saveData(data)
|
||||
.done(function() {
|
||||
self.setup(true);
|
||||
self.active = false;
|
||||
});
|
||||
self.settingsViewModel.saveData(data).done(function () {
|
||||
self.setup(true);
|
||||
self.active = false;
|
||||
});
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
function CoreWizardPluginBlacklistViewModel(parameters) {
|
||||
@@ -214,22 +244,26 @@ $(function() {
|
||||
self.required = false;
|
||||
self.active = false;
|
||||
|
||||
self.enablePluginBlacklist = function() {
|
||||
self.enablePluginBlacklist = function () {
|
||||
self.settingsViewModel.server_pluginBlacklist_enabled(true);
|
||||
self.decision(true);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.disablePluginBlacklist = function() {
|
||||
self.disablePluginBlacklist = function () {
|
||||
self.settingsViewModel.server_pluginBlacklist_enabled(false);
|
||||
self.decision(false);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
self.onBeforeWizardTabChange = function (next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_pluginblacklist_") || self.setup()) {
|
||||
if (
|
||||
!current ||
|
||||
!_.startsWith(current, "wizard_plugin_corewizard_pluginblacklist_") ||
|
||||
self.setup()
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -237,7 +271,7 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onBeforeWizardFinish = function() {
|
||||
self.onBeforeWizardFinish = function () {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (self.setup()) {
|
||||
@@ -248,18 +282,25 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.pluginblacklist && response.corewizard.details.pluginblacklist.required;
|
||||
self.onWizardDetails = function (response) {
|
||||
self.required =
|
||||
response &&
|
||||
response.corewizard &&
|
||||
response.corewizard.details &&
|
||||
response.corewizard.details.pluginblacklist &&
|
||||
response.corewizard.details.pluginblacklist.required;
|
||||
};
|
||||
|
||||
self._showDecisionNeededDialog = function() {
|
||||
self._showDecisionNeededDialog = function () {
|
||||
showMessageDialog({
|
||||
title: gettext("Please set up the plugin blacklist processing"),
|
||||
message: gettext("You haven't yet decided on whether to enable or disable the plugin blacklist processing. You need to either enable or disable it before continuing.")
|
||||
message: gettext(
|
||||
"You haven't yet decided on whether to enable or disable the plugin blacklist processing. You need to either enable or disable it before continuing."
|
||||
)
|
||||
});
|
||||
};
|
||||
|
||||
self._sendData = function() {
|
||||
self._sendData = function () {
|
||||
var data = {
|
||||
server: {
|
||||
pluginBlacklist: {
|
||||
@@ -269,13 +310,11 @@ $(function() {
|
||||
};
|
||||
|
||||
self.active = true;
|
||||
self.settingsViewModel.saveData(data)
|
||||
.done(function() {
|
||||
self.setup(true);
|
||||
self.active = false;
|
||||
});
|
||||
self.settingsViewModel.saveData(data).done(function () {
|
||||
self.setup(true);
|
||||
self.active = false;
|
||||
});
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
function CoreWizardPrinterProfileViewModel(parameters) {
|
||||
@@ -288,54 +327,68 @@ $(function() {
|
||||
self.editor = self.printerProfiles.createProfileEditor();
|
||||
self.editorLoaded = ko.observable(false);
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.printerprofile && response.corewizard.details.printerprofile.required;
|
||||
self.onWizardDetails = function (response) {
|
||||
self.required =
|
||||
response &&
|
||||
response.corewizard &&
|
||||
response.corewizard.details &&
|
||||
response.corewizard.details.printerprofile &&
|
||||
response.corewizard.details.printerprofile.required;
|
||||
if (!self.required) return;
|
||||
|
||||
OctoPrint.printerprofiles.get("_default")
|
||||
.done(function(data) {
|
||||
OctoPrint.printerprofiles
|
||||
.get("_default")
|
||||
.done(function (data) {
|
||||
self.editor.fromProfileData(data);
|
||||
self.editorLoaded(true);
|
||||
})
|
||||
.fail(function() {
|
||||
.fail(function () {
|
||||
self.editor.fromProfileData();
|
||||
self.editorLoaded(true);
|
||||
});
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
self.onWizardFinish = function () {
|
||||
if (!self.required) return;
|
||||
|
||||
OctoPrint.printerprofiles.update("_default", self.editor.toProfileData())
|
||||
.done(function() {
|
||||
OctoPrint.printerprofiles
|
||||
.update("_default", self.editor.toProfileData())
|
||||
.done(function () {
|
||||
self.printerProfiles.requestData();
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: CoreWizardAclViewModel,
|
||||
dependencies: ["loginStateViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_acl"]
|
||||
}, {
|
||||
construct: CoreWizardWebcamViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_webcam"]
|
||||
}, {
|
||||
construct: CoreWizardServerCommandsViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_servercommands"]
|
||||
}, {
|
||||
construct: CoreWizardOnlineCheckViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_onlinecheck"]
|
||||
}, {
|
||||
construct: CoreWizardPluginBlacklistViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_pluginblacklist"]
|
||||
}, {
|
||||
construct: CoreWizardPrinterProfileViewModel,
|
||||
dependencies: ["printerProfilesViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_printerprofile"]
|
||||
});
|
||||
OCTOPRINT_VIEWMODELS.push(
|
||||
{
|
||||
construct: CoreWizardAclViewModel,
|
||||
dependencies: ["loginStateViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_acl"]
|
||||
},
|
||||
{
|
||||
construct: CoreWizardWebcamViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_webcam"]
|
||||
},
|
||||
{
|
||||
construct: CoreWizardServerCommandsViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_servercommands"]
|
||||
},
|
||||
{
|
||||
construct: CoreWizardOnlineCheckViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_onlinecheck"]
|
||||
},
|
||||
{
|
||||
construct: CoreWizardPluginBlacklistViewModel,
|
||||
dependencies: ["settingsViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_pluginblacklist"]
|
||||
},
|
||||
{
|
||||
construct: CoreWizardPrinterProfileViewModel,
|
||||
dependencies: ["printerProfilesViewModel"],
|
||||
elements: ["#wizard_plugin_corewizard_printerprofile"]
|
||||
}
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function ErrorTrackingViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -6,7 +6,7 @@ $(function() {
|
||||
self.loginState = parameters[1];
|
||||
|
||||
var notification = undefined;
|
||||
var performCheck = function() {
|
||||
var performCheck = function () {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
// already enabled?
|
||||
@@ -19,7 +19,8 @@ $(function() {
|
||||
|
||||
// ignored?
|
||||
try {
|
||||
var ignoredString = localStorage["plugin.errortracking.notification_ignored"];
|
||||
var ignoredString =
|
||||
localStorage["plugin.errortracking.notification_ignored"];
|
||||
var ignored = false;
|
||||
|
||||
if (ignoredString) {
|
||||
@@ -28,50 +29,63 @@ $(function() {
|
||||
|
||||
if (ignored) return;
|
||||
} catch (ex) {
|
||||
log.error("Error while reading plugin.errortracking.notification_ignored from local storage");
|
||||
log.error(
|
||||
"Error while reading plugin.errortracking.notification_ignored from local storage"
|
||||
);
|
||||
}
|
||||
|
||||
// show notification
|
||||
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>"),
|
||||
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() {
|
||||
buttons: [
|
||||
{
|
||||
text: gettext("Ignore"),
|
||||
click: function () {
|
||||
notification.remove();
|
||||
notification = undefined;
|
||||
location.reload(true);
|
||||
});
|
||||
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,
|
||||
@@ -79,7 +93,7 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
// not an RC release channel, close notification
|
||||
// not an RC release channel, close notification
|
||||
} else if (notification !== undefined) {
|
||||
notification.remove();
|
||||
notification = undefined;
|
||||
@@ -87,11 +101,19 @@ $(function() {
|
||||
};
|
||||
|
||||
var subbed = false;
|
||||
self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function () {
|
||||
performCheck();
|
||||
if (self.settings && self.settings.settings && self.settings.settings.plugins && self.settings.settings.plugins.softwareupdate && !subbed) {
|
||||
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);
|
||||
self.settings.settings.plugins.softwareupdate.octoprint_release_channel.subscribe(
|
||||
performCheck
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function GcodeViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -11,15 +11,23 @@ $(function() {
|
||||
|
||||
self.ui_progress_percentage = ko.observable();
|
||||
self.ui_progress_type = ko.observable();
|
||||
self.ui_progress_text = ko.pureComputed(function() {
|
||||
self.ui_progress_text = ko.pureComputed(function () {
|
||||
var text = "";
|
||||
switch (self.ui_progress_type()) {
|
||||
case "loading": {
|
||||
text = gettext("Loading...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
|
||||
text =
|
||||
gettext("Loading...") +
|
||||
" (" +
|
||||
self.ui_progress_percentage().toFixed(0) +
|
||||
"%)";
|
||||
break;
|
||||
}
|
||||
case "analyzing": {
|
||||
text = gettext("Analyzing...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
|
||||
text =
|
||||
gettext("Analyzing...") +
|
||||
" (" +
|
||||
self.ui_progress_percentage().toFixed(0) +
|
||||
"%)";
|
||||
break;
|
||||
}
|
||||
case "done": {
|
||||
@@ -68,12 +76,18 @@ $(function() {
|
||||
self.layerUpEnabled = ko.observable(false);
|
||||
self.layerDownEnabled = ko.observable(false);
|
||||
|
||||
self.synchronizeOptionsAndReload = function(additionalRendererOptions, additionalReaderOptions) {
|
||||
self.synchronizeOptionsAndReload = function (
|
||||
additionalRendererOptions,
|
||||
additionalReaderOptions
|
||||
) {
|
||||
self.synchronizeOptions(additionalRendererOptions, additionalReaderOptions);
|
||||
self.reload();
|
||||
};
|
||||
|
||||
self.synchronizeOptions = function(additionalRendererOptions, additionalReaderOptions) {
|
||||
self.synchronizeOptions = function (
|
||||
additionalRendererOptions,
|
||||
additionalReaderOptions
|
||||
) {
|
||||
var renderer = {
|
||||
moveModel: self.renderer_centerModel(),
|
||||
centerViewport: self.renderer_centerViewport(),
|
||||
@@ -82,7 +96,9 @@ $(function() {
|
||||
showHead: self.renderer_showPrinthead(),
|
||||
showBoundingBox: self.renderer_showBoundingBox(),
|
||||
showFullSize: self.renderer_showFullSize(),
|
||||
extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1,
|
||||
extrusionWidth: self.renderer_extrusionWidthEnabled()
|
||||
? self.renderer_extrusionWidth()
|
||||
: 1,
|
||||
showNextLayer: self.renderer_showNext(),
|
||||
showCurrentLayer: self.renderer_showCurrent(),
|
||||
showPreviousLayer: self.renderer_showPrevious(),
|
||||
@@ -96,7 +112,7 @@ $(function() {
|
||||
var reader = {
|
||||
sortLayers: self.reader_sortLayers(),
|
||||
purgeEmptyLayers: self.reader_hideEmptyLayers(),
|
||||
ignoreOutsideBed: self.reader_ignoreOutsideBed(),
|
||||
ignoreOutsideBed: self.reader_ignoreOutsideBed()
|
||||
};
|
||||
if (additionalReaderOptions) {
|
||||
_.extend(reader, additionalReaderOptions);
|
||||
@@ -108,12 +124,12 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.rendererOptionUpdated = function() {
|
||||
self.rendererOptionUpdated = function () {
|
||||
self.synchronizeOptions();
|
||||
self._toLocalStorage();
|
||||
};
|
||||
|
||||
self.readerOptionUpdated = function() {
|
||||
self.readerOptionUpdated = function () {
|
||||
self.synchronizeOptionsAndReload();
|
||||
self._toLocalStorage();
|
||||
};
|
||||
@@ -137,7 +153,7 @@ $(function() {
|
||||
self.reader_hideEmptyLayers.subscribe(self.readerOptionUpdated);
|
||||
self.reader_ignoreOutsideBed.subscribe(self.readerOptionUpdated);
|
||||
|
||||
self._printerProfileUpdated = function() {
|
||||
self._printerProfileUpdated = function () {
|
||||
if (!self.enabled) return;
|
||||
|
||||
var currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
@@ -168,27 +184,43 @@ $(function() {
|
||||
};
|
||||
|
||||
// subscribe to relevant printer settings...
|
||||
self.settings.printerProfiles.currentProfileData.subscribe(function() {
|
||||
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);
|
||||
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.width.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles
|
||||
.currentProfileData()
|
||||
.volume.depth.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles
|
||||
.currentProfileData()
|
||||
.volume.formFactor.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.printerProfiles
|
||||
.currentProfileData()
|
||||
.axes.x.inverted.subscribe(self._printerProfileUpdated);
|
||||
self.settings.printerProfiles
|
||||
.currentProfileData()
|
||||
.axes.y.inverted.subscribe(self._printerProfileUpdated);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
self.settings.feature_g90InfluencesExtruder.subscribe(function() {
|
||||
self.settings.feature_g90InfluencesExtruder.subscribe(function () {
|
||||
GCODE.ui.updateOptions({
|
||||
reader: {
|
||||
g90InfluencesExtruder: self.settings.feature_g90InfluencesExtruder()
|
||||
@@ -196,13 +228,23 @@ $(function() {
|
||||
});
|
||||
});
|
||||
|
||||
self._retrieveBedDimensions = function(currentProfileData) {
|
||||
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;
|
||||
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") {
|
||||
@@ -229,32 +271,35 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._retrieveToolOffsets = function(currentProfileData) {
|
||||
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]})
|
||||
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) {
|
||||
self._retrieveAxesConfiguration = function (currentProfileData) {
|
||||
if (currentProfileData == undefined) {
|
||||
currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
}
|
||||
|
||||
if (currentProfileData && currentProfileData.axes) {
|
||||
var invertX = false, invertY = false;
|
||||
var invertX = false,
|
||||
invertY = false;
|
||||
if (currentProfileData.axes.x) {
|
||||
invertX = currentProfileData.axes.x.inverted();
|
||||
}
|
||||
@@ -265,7 +310,7 @@ $(function() {
|
||||
return {
|
||||
x: invertX,
|
||||
y: invertY
|
||||
}
|
||||
};
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
@@ -273,7 +318,7 @@ $(function() {
|
||||
|
||||
self.loadedFilepath = undefined;
|
||||
self.loadedFileDate = undefined;
|
||||
self.status = 'idle';
|
||||
self.status = "idle";
|
||||
self.enabled = false;
|
||||
|
||||
self.currentlyPrinting = false;
|
||||
@@ -287,52 +332,61 @@ $(function() {
|
||||
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.initialize = function () {
|
||||
self.sizeThresholdStr = sizeObservable(
|
||||
self.settings.settings.plugins.gcodeviewer.sizeThreshold
|
||||
);
|
||||
self.mobileSizeThresholdStr = sizeObservable(
|
||||
self.settings.settings.plugins.gcodeviewer.mobileSizeThreshold
|
||||
);
|
||||
|
||||
var layerSliderElement = $("#gcode_slider_layers");
|
||||
var commandSliderElement = $("#gcode_slider_commands");
|
||||
var containerElement = $("#gcode_canvas");
|
||||
|
||||
if (!(layerSliderElement.length && commandSliderElement.length && containerElement.length)) {
|
||||
if (
|
||||
!(
|
||||
layerSliderElement.length &&
|
||||
commandSliderElement.length &&
|
||||
containerElement.length
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
self._configureLayerSlider(layerSliderElement);
|
||||
self._configureLayerCommandSlider(commandSliderElement);
|
||||
|
||||
self.settings.firstRequest
|
||||
.done(function() {
|
||||
var initResult = GCODE.ui.init({
|
||||
container: "#gcode_canvas",
|
||||
onProgress: self._onProgress,
|
||||
onModelLoaded: self._onModelLoaded,
|
||||
onLayerSelected: self._onLayerSelected,
|
||||
bed: self._retrieveBedDimensions(),
|
||||
toolOffsets: self._retrieveToolOffsets(),
|
||||
invertAxes: self._retrieveAxesConfiguration()
|
||||
});
|
||||
|
||||
if (!initResult) {
|
||||
log.info("Could not initialize GCODE viewer component");
|
||||
return;
|
||||
}
|
||||
|
||||
self.synchronizeOptions();
|
||||
self.enabled = true;
|
||||
self._fromLocalStorage();
|
||||
self.settings.firstRequest.done(function () {
|
||||
var initResult = GCODE.ui.init({
|
||||
container: "#gcode_canvas",
|
||||
onProgress: self._onProgress,
|
||||
onModelLoaded: self._onModelLoaded,
|
||||
onLayerSelected: self._onLayerSelected,
|
||||
bed: self._retrieveBedDimensions(),
|
||||
toolOffsets: self._retrieveToolOffsets(),
|
||||
invertAxes: self._retrieveAxesConfiguration()
|
||||
});
|
||||
|
||||
if (!initResult) {
|
||||
log.info("Could not initialize GCODE viewer component");
|
||||
return;
|
||||
}
|
||||
|
||||
self.synchronizeOptions();
|
||||
self.enabled = true;
|
||||
self._fromLocalStorage();
|
||||
});
|
||||
};
|
||||
|
||||
self.reset = function() {
|
||||
self.reset = function () {
|
||||
self.enableReload(false);
|
||||
self.loadedFilepath = undefined;
|
||||
self.loadedFileDate = undefined;
|
||||
self.clear();
|
||||
};
|
||||
|
||||
self.resetOptions = function() {
|
||||
self.resetOptions = function () {
|
||||
self.renderer_centerModel(false);
|
||||
self.renderer_centerViewport(false);
|
||||
self.renderer_zoomOnModel(false);
|
||||
@@ -353,46 +407,59 @@ $(function() {
|
||||
self.reader_ignoreOutsideBed(true);
|
||||
};
|
||||
|
||||
self.clear = function() {
|
||||
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._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,
|
||||
tooltip: "hide"
|
||||
}).on("slide", self.changeCommandRange);
|
||||
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,
|
||||
tooltip: "hide"
|
||||
})
|
||||
.on("slide", self.changeCommandRange);
|
||||
};
|
||||
|
||||
self.loadFile = function(path, date){
|
||||
self.loadFile = function (path, date) {
|
||||
self.enableReload(false);
|
||||
self.needsLoad = false;
|
||||
if (self.status === "idle" && self.errorCount < 3) {
|
||||
self.status = "request";
|
||||
OctoPrint.files.download("local", path)
|
||||
.done(function(response, rstatus) {
|
||||
if(rstatus === 'success'){
|
||||
OctoPrint.files
|
||||
.download("local", path)
|
||||
.done(function (response, rstatus) {
|
||||
if (rstatus === "success") {
|
||||
self.showGCodeViewer(response, rstatus);
|
||||
self.loadedFilepath = path;
|
||||
self.loadedFileDate = date;
|
||||
@@ -400,14 +467,14 @@ $(function() {
|
||||
self.enableReload(true);
|
||||
}
|
||||
})
|
||||
.fail(function() {
|
||||
.fail(function () {
|
||||
self.status = "idle";
|
||||
self.errorCount++;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
self.showGCodeViewer = function(response, rstatus) {
|
||||
self.showGCodeViewer = function (response, rstatus) {
|
||||
var par = {
|
||||
target: {
|
||||
result: response
|
||||
@@ -424,20 +491,20 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.reload = function() {
|
||||
self.reload = function () {
|
||||
if (!self.enableReload()) return;
|
||||
self.loadFile(self.loadedFilepath, self.loadedFileDate);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self.fromHistoryData = function (data) {
|
||||
self._processData(data);
|
||||
};
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self.fromCurrentData = function (data) {
|
||||
self._processData(data);
|
||||
};
|
||||
|
||||
self._renderPercentage = function(percentage) {
|
||||
self._renderPercentage = function (percentage) {
|
||||
var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(percentage);
|
||||
if (!cmdIndex) return;
|
||||
|
||||
@@ -452,8 +519,11 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._processData = function(data) {
|
||||
if (!data.job.file || !data.job.file.path && (self.loadedFilepath || self.loadedFileDate)) {
|
||||
self._processData = function (data) {
|
||||
if (
|
||||
!data.job.file ||
|
||||
(!data.job.file.path && (self.loadedFilepath || self.loadedFileDate))
|
||||
) {
|
||||
self.waitForApproval(false);
|
||||
|
||||
self.loadedFilepath = undefined;
|
||||
@@ -466,26 +536,46 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
if (!self.enabled) return;
|
||||
self.currentlyPrinting = data.state.flags && (data.state.flags.printing || data.state.flags.paused);
|
||||
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) {
|
||||
if (OctoPrint.coreui.browserTabVisible && self.tabActive && self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
|
||||
if (
|
||||
self.loadedFilepath &&
|
||||
self.loadedFilepath === data.job.file.path &&
|
||||
self.loadedFileDate === data.job.file.date
|
||||
) {
|
||||
if (
|
||||
OctoPrint.coreui.browserTabVisible &&
|
||||
self.tabActive &&
|
||||
self.currentlyPrinting &&
|
||||
self.renderer_syncProgress() &&
|
||||
!self.waitForApproval()
|
||||
) {
|
||||
self._renderPercentage(data.progress.completion);
|
||||
}
|
||||
self.errorCount = 0
|
||||
self.errorCount = 0;
|
||||
} else {
|
||||
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)) {
|
||||
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.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())) {
|
||||
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;
|
||||
@@ -501,23 +591,23 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.onEventPrintDone = function() {
|
||||
self.onEventPrintDone = function () {
|
||||
if (self.renderer_syncProgress() && !self.waitForApproval()) {
|
||||
self._renderPercentage(100.0);
|
||||
}
|
||||
};
|
||||
|
||||
self.approveLargeFile = function() {
|
||||
self.approveLargeFile = function () {
|
||||
self.waitForApproval(false);
|
||||
self.loadFile(self.selectedFile.path(), self.selectedFile.date());
|
||||
};
|
||||
|
||||
self._onProgress = function(type, percentage) {
|
||||
self._onProgress = function (type, percentage) {
|
||||
self.ui_progress_type(type);
|
||||
self.ui_progress_percentage(percentage);
|
||||
};
|
||||
|
||||
self._onModelLoaded = function(model) {
|
||||
self._onModelLoaded = function (model) {
|
||||
if (!model) {
|
||||
self.ui_modelInfo("");
|
||||
if (self.layerSlider !== undefined) {
|
||||
@@ -532,10 +622,32 @@ $(function() {
|
||||
self.maxLayer = 0;
|
||||
} else {
|
||||
var output = [];
|
||||
output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm × " + model.depth.toFixed(2) + "mm × " + 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));
|
||||
output.push(
|
||||
gettext("Model size") +
|
||||
": " +
|
||||
model.width.toFixed(2) +
|
||||
"mm × " +
|
||||
model.depth.toFixed(2) +
|
||||
"mm × " +
|
||||
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>"));
|
||||
|
||||
@@ -551,7 +663,7 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._onLayerSelected = function(layer) {
|
||||
self._onLayerSelected = function (layer) {
|
||||
if (!layer) {
|
||||
self.ui_layerInfo("");
|
||||
if (self.layerCommandSlider !== undefined) {
|
||||
@@ -570,16 +682,34 @@ $(function() {
|
||||
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");
|
||||
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("Filament") +
|
||||
" (" +
|
||||
gettext("Tool") +
|
||||
" " +
|
||||
i +
|
||||
"): " +
|
||||
layer.filament[i].toFixed(2) +
|
||||
"mm"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
output.push(gettext("Estimated print time") + ": " + formatDuration(layer.printTime));
|
||||
output.push(
|
||||
gettext("Estimated print time") +
|
||||
": " +
|
||||
formatDuration(layer.printTime)
|
||||
);
|
||||
|
||||
self.ui_layerInfo(output.join("<br>"));
|
||||
|
||||
@@ -594,23 +724,33 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._onInternalRendererOptionChange = function(options) {
|
||||
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()) {
|
||||
if (
|
||||
opt === "zoomInOnModel" &&
|
||||
options[opt] !== self.renderer_zoomOnModel()
|
||||
) {
|
||||
self.renderer_zoomOnModel(false);
|
||||
} else if (opt === "centerViewport" && options[opt] !== self.renderer_centerViewport()) {
|
||||
} else if (
|
||||
opt === "centerViewport" &&
|
||||
options[opt] !== self.renderer_centerViewport()
|
||||
) {
|
||||
self.renderer_centerViewport(false);
|
||||
} else if (opt === "moveModel" && options[opt] !== self.renderer_centerModel()) {
|
||||
} 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);
|
||||
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;
|
||||
@@ -619,20 +759,23 @@ $(function() {
|
||||
GCODE.ui.changeSelectedLayer(value);
|
||||
};
|
||||
|
||||
self.onMouseOver = function(data, event) {
|
||||
self.onMouseOver = function (data, event) {
|
||||
if (!self.settings.feature_keyboardControl()) return;
|
||||
$("#canvas_container").focus();
|
||||
|
||||
};
|
||||
self.onMouseOut = function(data, event) {
|
||||
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;
|
||||
self.onKeyDown = function (data, event) {
|
||||
if (
|
||||
!self.settings.feature_keyboardControl() ||
|
||||
self.layerSlider === undefined
|
||||
)
|
||||
return;
|
||||
|
||||
var value = self.currentLayer;
|
||||
switch(event.which){
|
||||
switch (event.which) {
|
||||
case 33: // Pg up
|
||||
value = value + 10; // No need to check against max this is done by the Slider anyway
|
||||
break;
|
||||
@@ -649,65 +792,75 @@ $(function() {
|
||||
self.shiftLayer(value);
|
||||
};
|
||||
|
||||
self.changeCommandRange = function(event) {
|
||||
if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);
|
||||
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;
|
||||
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]);
|
||||
GCODE.ui.changeSelectedCommands(
|
||||
self.layerSlider.slider("getValue"),
|
||||
tuple[0],
|
||||
tuple[1]
|
||||
);
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.onDataUpdaterReconnect = function () {
|
||||
self.reset();
|
||||
};
|
||||
|
||||
self.onBeforeBinding = function() {
|
||||
self.onBeforeBinding = function () {
|
||||
self.initialize();
|
||||
};
|
||||
|
||||
self.onTabChange = function(current, previous) {
|
||||
self.onTabChange = function (current, previous) {
|
||||
self.tabActive = current === "#gcode";
|
||||
if (self.tabActive && self.needsLoad) {
|
||||
self.loadFile(self.selectedFile.path(), self.selectedFile.date());
|
||||
}
|
||||
};
|
||||
|
||||
self.shiftLayer = function(value){
|
||||
self.shiftLayer = function (value) {
|
||||
if (value !== self.currentLayer) {
|
||||
self.layerSlider.slider('setValue', value);
|
||||
value = self.layerSlider.slider('getValue');
|
||||
self.layerSlider.slider("setValue", value);
|
||||
value = self.layerSlider.slider("getValue");
|
||||
//This sets the scroll bar to the appropriate position.
|
||||
self.layerSlider
|
||||
.trigger({
|
||||
type: 'slideStart',
|
||||
type: "slideStart",
|
||||
value: value
|
||||
})
|
||||
.trigger({
|
||||
type: 'slide',
|
||||
type: "slide",
|
||||
value: value
|
||||
}).trigger({
|
||||
type: 'slideStop',
|
||||
})
|
||||
.trigger({
|
||||
type: "slideStop",
|
||||
value: value
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
self.incrementLayer = function() {
|
||||
var value = self.layerSlider.slider('getValue') + 1;
|
||||
self.incrementLayer = function () {
|
||||
var value = self.layerSlider.slider("getValue") + 1;
|
||||
self.shiftLayer(value);
|
||||
};
|
||||
|
||||
self.decrementLayer = function() {
|
||||
var value = self.layerSlider.slider('getValue') - 1;
|
||||
self.decrementLayer = function () {
|
||||
var value = self.layerSlider.slider("getValue") - 1;
|
||||
self.shiftLayer(value);
|
||||
};
|
||||
|
||||
var optionsLocalStorageKey = "core.gcodeviewer.options";
|
||||
self._toLocalStorage = function() {
|
||||
if (!Modernizr.localstorage)
|
||||
return;
|
||||
self._toLocalStorage = function () {
|
||||
if (!Modernizr.localstorage) return;
|
||||
|
||||
var current = {};
|
||||
current["centerViewport"] = self.renderer_centerViewport();
|
||||
@@ -725,11 +878,10 @@ $(function() {
|
||||
|
||||
localStorage[optionsLocalStorageKey] = JSON.stringify(current);
|
||||
};
|
||||
self._fromLocalStorage = function() {
|
||||
self._fromLocalStorage = function () {
|
||||
self.resetOptions();
|
||||
|
||||
if (!Modernizr.localstorage)
|
||||
return;
|
||||
if (!Modernizr.localstorage) return;
|
||||
|
||||
var currentString = localStorage[optionsLocalStorageKey];
|
||||
var current;
|
||||
@@ -743,18 +895,30 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
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["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["hideEmptyLayers"] !== undefined) self.reader_hideEmptyLayers(current["hideEmptyLayers"]) ;
|
||||
if (current["sortLayers"] !== undefined) self.reader_sortLayers(current["sortLayers"]) ;
|
||||
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["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["hideEmptyLayers"] !== undefined)
|
||||
self.reader_hideEmptyLayers(current["hideEmptyLayers"]);
|
||||
if (current["sortLayers"] !== undefined)
|
||||
self.reader_sortLayers(current["sortLayers"]);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -4,30 +4,33 @@
|
||||
* Time: 7:31 AM
|
||||
*/
|
||||
|
||||
GCODE.gCodeReader = (function(){
|
||||
// ***** PRIVATE ******
|
||||
GCODE.gCodeReader = (function () {
|
||||
// ***** PRIVATE ******
|
||||
var gcode, lines;
|
||||
var z_heights = {};
|
||||
var model = [];
|
||||
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 boundingBox = {
|
||||
minX: undefined,
|
||||
maxX: undefined,
|
||||
minY: undefined,
|
||||
maxY: undefined,
|
||||
minZ: undefined,
|
||||
maxZ: undefined
|
||||
};
|
||||
var filamentByLayer = {};
|
||||
var printTimeByLayer;
|
||||
var totalFilament=0;
|
||||
var printTime=0;
|
||||
var totalFilament = 0;
|
||||
var printTime = 0;
|
||||
var speeds = {};
|
||||
var speedsByLayer = {};
|
||||
var gCodeOptions = {
|
||||
sortLayers: false,
|
||||
purgeEmptyLayers: true,
|
||||
analyzeModel: false,
|
||||
toolOffsets: [
|
||||
{x: 0, y: 0}
|
||||
],
|
||||
toolOffsets: [{x: 0, y: 0}],
|
||||
bed: {
|
||||
x: undefined,
|
||||
y: undefined,
|
||||
@@ -41,39 +44,39 @@ GCODE.gCodeReader = (function(){
|
||||
|
||||
var percentageTree = undefined;
|
||||
|
||||
var prepareGCode = function(totalSize){
|
||||
if(!lines)return;
|
||||
var prepareGCode = function (totalSize) {
|
||||
if (!lines) return;
|
||||
gcode = [];
|
||||
var i, byteCount;
|
||||
|
||||
byteCount = 0;
|
||||
for(i=0;i<lines.length;i++){
|
||||
for (i = 0; i < lines.length; i++) {
|
||||
byteCount += lines[i].length + 1; // line length + line ending
|
||||
gcode.push({line: lines[i], percentage: byteCount * 100 / totalSize});
|
||||
gcode.push({line: lines[i], percentage: (byteCount * 100) / totalSize});
|
||||
}
|
||||
lines = [];
|
||||
};
|
||||
|
||||
var sortLayers = function(m){
|
||||
var sortLayers = function (m) {
|
||||
var sortedZ = [];
|
||||
var tmpModel = [];
|
||||
|
||||
for(var layer in z_heights){
|
||||
for (var layer in z_heights) {
|
||||
sortedZ[z_heights[layer]] = layer;
|
||||
}
|
||||
|
||||
sortedZ.sort(function(a,b){
|
||||
return a-b;
|
||||
sortedZ.sort(function (a, b) {
|
||||
return a - b;
|
||||
});
|
||||
|
||||
for(var i=0;i<sortedZ.length;i++){
|
||||
if(typeof(z_heights[sortedZ[i]]) === 'undefined')continue;
|
||||
for (var i = 0; i < sortedZ.length; i++) {
|
||||
if (typeof z_heights[sortedZ[i]] === "undefined") continue;
|
||||
tmpModel[i] = m[z_heights[sortedZ[i]]];
|
||||
}
|
||||
return tmpModel;
|
||||
};
|
||||
|
||||
var prepareLinesIndex = function(m){
|
||||
var prepareLinesIndex = function (m) {
|
||||
percentageTree = undefined;
|
||||
|
||||
for (var l = 0; l < m.length; l++) {
|
||||
@@ -90,7 +93,7 @@ GCODE.gCodeReader = (function(){
|
||||
}
|
||||
};
|
||||
|
||||
var searchInPercentageTree = function(key) {
|
||||
var searchInPercentageTree = function (key) {
|
||||
if (percentageTree === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -103,17 +106,17 @@ GCODE.gCodeReader = (function(){
|
||||
return elements[0];
|
||||
};
|
||||
|
||||
var purgeLayers = function(m){
|
||||
if(!m) return;
|
||||
var purgeLayers = function (m) {
|
||||
if (!m) return;
|
||||
var tmpModel = [];
|
||||
|
||||
var purge;
|
||||
for(var i = 0; i < m.length; i++){
|
||||
for (var i = 0; i < m.length; i++) {
|
||||
purge = true;
|
||||
|
||||
if (typeof(m[i]) !== "undefined") {
|
||||
if (typeof m[i] !== "undefined") {
|
||||
for (var j = 0; j < m[i].length; j++) {
|
||||
if(m[i][j].extrude) {
|
||||
if (m[i][j].extrude) {
|
||||
purge = false;
|
||||
break;
|
||||
}
|
||||
@@ -128,20 +131,25 @@ GCODE.gCodeReader = (function(){
|
||||
return tmpModel;
|
||||
};
|
||||
|
||||
// ***** PUBLIC *******
|
||||
// ***** PUBLIC *******
|
||||
return {
|
||||
clear: function() {
|
||||
clear: function () {
|
||||
model = [];
|
||||
z_heights = [];
|
||||
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};
|
||||
boundingBox = {
|
||||
minX: undefined,
|
||||
maxX: undefined,
|
||||
minY: undefined,
|
||||
maxY: undefined,
|
||||
minZ: undefined,
|
||||
maxZ: undefined
|
||||
};
|
||||
},
|
||||
|
||||
loadFile: function(reader){
|
||||
loadFile: function (reader) {
|
||||
this.clear();
|
||||
|
||||
var totalSize = reader.target.result.length;
|
||||
@@ -150,26 +158,25 @@ GCODE.gCodeReader = (function(){
|
||||
prepareGCode(totalSize);
|
||||
|
||||
GCODE.ui.worker.postMessage({
|
||||
"cmd":"parseGCode",
|
||||
"msg":{
|
||||
gcode: gcode,
|
||||
options: {
|
||||
firstReport: 5,
|
||||
toolOffsets: gCodeOptions["toolOffsets"],
|
||||
bed: gCodeOptions["bed"],
|
||||
ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"],
|
||||
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"]
|
||||
}
|
||||
cmd: "parseGCode",
|
||||
msg: {
|
||||
gcode: gcode,
|
||||
options: {
|
||||
firstReport: 5,
|
||||
toolOffsets: gCodeOptions["toolOffsets"],
|
||||
bed: gCodeOptions["bed"],
|
||||
ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"],
|
||||
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"]
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
},
|
||||
|
||||
setOption: function(options){
|
||||
setOption: function (options) {
|
||||
var dirty = false;
|
||||
for(var opt in options){
|
||||
for (var opt in options) {
|
||||
if (options[opt] === undefined) continue;
|
||||
dirty = dirty || (gCodeOptions[opt] != options[opt]);
|
||||
dirty = dirty || gCodeOptions[opt] != options[opt];
|
||||
gCodeOptions[opt] = options[opt];
|
||||
}
|
||||
if (dirty) {
|
||||
@@ -177,7 +184,7 @@ GCODE.gCodeReader = (function(){
|
||||
}
|
||||
},
|
||||
|
||||
passDataToRenderer: function(){
|
||||
passDataToRenderer: function () {
|
||||
var m = model;
|
||||
if (gCodeOptions["sortLayers"]) m = sortLayers(m);
|
||||
if (gCodeOptions["purgeEmptyLayers"]) m = purgeLayers(m);
|
||||
@@ -186,19 +193,19 @@ GCODE.gCodeReader = (function(){
|
||||
return m;
|
||||
},
|
||||
|
||||
processLayerFromWorker: function(msg){
|
||||
processLayerFromWorker: function (msg) {
|
||||
model[msg.layerNum] = msg.cmds;
|
||||
z_heights[msg.zHeightObject.zValue] = msg.zHeightObject.layer;
|
||||
},
|
||||
|
||||
processMultiLayerFromWorker: function(msg){
|
||||
for(var i=0;i<msg.layerNum.length;i++){
|
||||
processMultiLayerFromWorker: function (msg) {
|
||||
for (var i = 0; i < msg.layerNum.length; i++) {
|
||||
model[msg.layerNum[i]] = msg.model[msg.layerNum[i]];
|
||||
z_heights[msg.zHeightObject.zValue[i]] = msg.layerNum[i];
|
||||
}
|
||||
},
|
||||
|
||||
processAnalyzeModelDone: function(msg){
|
||||
processAnalyzeModelDone: function (msg) {
|
||||
min = msg.min;
|
||||
max = msg.max;
|
||||
modelSize = msg.modelSize;
|
||||
@@ -211,15 +218,15 @@ GCODE.gCodeReader = (function(){
|
||||
printTimeByLayer = msg.printTimeByLayer;
|
||||
},
|
||||
|
||||
getLayerFilament: function(z){
|
||||
getLayerFilament: function (z) {
|
||||
return filamentByLayer[z];
|
||||
},
|
||||
|
||||
getLayerSpeeds: function(z){
|
||||
return speedsByLayer[z]?speedsByLayer[z]:{};
|
||||
getLayerSpeeds: function (z) {
|
||||
return speedsByLayer[z] ? speedsByLayer[z] : {};
|
||||
},
|
||||
|
||||
getModelInfo: function(){
|
||||
getModelInfo: function () {
|
||||
return {
|
||||
min: min,
|
||||
max: max,
|
||||
@@ -233,7 +240,7 @@ GCODE.gCodeReader = (function(){
|
||||
};
|
||||
},
|
||||
|
||||
getGCodeLines: function(layer, fromSegments, toSegments){
|
||||
getGCodeLines: function (layer, fromSegments, toSegments) {
|
||||
var result = {
|
||||
first: model[layer][fromSegments].gcodeLine,
|
||||
last: model[layer][toSegments].gcodeLine
|
||||
@@ -241,13 +248,13 @@ GCODE.gCodeReader = (function(){
|
||||
return result;
|
||||
},
|
||||
|
||||
getCmdIndexForPercentage: function(percentage) {
|
||||
getCmdIndexForPercentage: function (percentage) {
|
||||
var command = searchInPercentageTree(percentage);
|
||||
if (command === undefined) {
|
||||
return undefined
|
||||
return undefined;
|
||||
} else {
|
||||
return command.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}());
|
||||
};
|
||||
})();
|
||||
@@ -5,9 +5,8 @@
|
||||
* To change this template use File | Settings | File Templates.
|
||||
*/
|
||||
|
||||
|
||||
GCODE.renderer = (function(){
|
||||
// ***** PRIVATE ******
|
||||
GCODE.renderer = (function () {
|
||||
// ***** PRIVATE ******
|
||||
var canvas;
|
||||
var ctx;
|
||||
|
||||
@@ -15,12 +14,14 @@ GCODE.renderer = (function(){
|
||||
var lineWidthFactor = 1 / 2.8;
|
||||
|
||||
var zoomFactorDelta = 0.4;
|
||||
var gridStep=10;
|
||||
var gridStep = 10;
|
||||
var ctxHeight, ctxWidth;
|
||||
var prevX=0, prevY=0;
|
||||
var prevX = 0,
|
||||
prevY = 0;
|
||||
var pixelRatio = window.devicePixelRatio || 1;
|
||||
|
||||
var layerNumStore, progressStore={from: 0, to: -1};
|
||||
var layerNumStore,
|
||||
progressStore = {from: 0, to: -1};
|
||||
var lastX, lastY;
|
||||
var dragStart;
|
||||
var scaleFactor = 1.1;
|
||||
@@ -65,16 +66,20 @@ GCODE.renderer = (function(){
|
||||
|
||||
onViewportChange: undefined,
|
||||
onDragStart: undefined, // Cancellable (return false)
|
||||
onDrag: undefined, // Cancellable (return false)
|
||||
onDrag: undefined, // Cancellable (return false)
|
||||
onDragStop: undefined
|
||||
};
|
||||
|
||||
var offsetModelX = 0, offsetModelY = 0;
|
||||
var offsetBedX = 0, offsetBedY = 0;
|
||||
var scaleX = 1, scaleY = 1;
|
||||
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 currentInvertX = false,
|
||||
currentInvertY = false;
|
||||
|
||||
function notifyIfViewportChanged() {
|
||||
if (viewportChanged) {
|
||||
@@ -85,29 +90,52 @@ GCODE.renderer = (function(){
|
||||
}
|
||||
}
|
||||
|
||||
var reRender = function(){
|
||||
var reRender = function () {
|
||||
if (!model) return;
|
||||
|
||||
log.debug("Rerendering layer " + layerNumStore + " of " + model.length + " with " + GCODE.renderer.getLayerNumSegments(layerNumStore) + " segments");
|
||||
log.debug(
|
||||
"Rerendering layer " +
|
||||
layerNumStore +
|
||||
" of " +
|
||||
model.length +
|
||||
" with " +
|
||||
GCODE.renderer.getLayerNumSegments(layerNumStore) +
|
||||
" segments"
|
||||
);
|
||||
|
||||
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);
|
||||
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();
|
||||
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["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["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);
|
||||
if (renderOptions["showPreviousLayer"] && layerNumStore > 0) {
|
||||
drawLayer(
|
||||
layerNumStore - 1,
|
||||
0,
|
||||
GCODE.renderer.getLayerNumSegments(layerNumStore - 1),
|
||||
true
|
||||
);
|
||||
}
|
||||
drawLayer(layerNumStore, progressStore.from, progressStore.to);
|
||||
} else {
|
||||
@@ -116,52 +144,59 @@ GCODE.renderer = (function(){
|
||||
}
|
||||
};
|
||||
|
||||
function trackTransforms(ctx){
|
||||
var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
|
||||
function trackTransforms(ctx) {
|
||||
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
var xform = svg.createSVGMatrix();
|
||||
ctx.getTransform = function(){ return xform; };
|
||||
ctx.getTransform = function () {
|
||||
return xform;
|
||||
};
|
||||
|
||||
var savedTransforms = [];
|
||||
var save = ctx.save;
|
||||
ctx.save = function(){
|
||||
savedTransforms.push(xform.translate(0,0));
|
||||
ctx.save = function () {
|
||||
savedTransforms.push(xform.translate(0, 0));
|
||||
return save.call(ctx);
|
||||
};
|
||||
var restore = ctx.restore;
|
||||
ctx.restore = function(){
|
||||
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);
|
||||
ctx.scale = function (sx, sy) {
|
||||
xform = xform.scaleNonUniform(sx, sy);
|
||||
viewportChanged = true;
|
||||
return scale.call(ctx,sx,sy);
|
||||
return scale.call(ctx, sx, sy);
|
||||
};
|
||||
var rotate = ctx.rotate;
|
||||
ctx.rotate = function(radians){
|
||||
xform = xform.rotate(radians*180/Math.PI);
|
||||
ctx.rotate = function (radians) {
|
||||
xform = xform.rotate((radians * 180) / Math.PI);
|
||||
viewportChanged = true;
|
||||
return rotate.call(ctx,radians);
|
||||
return rotate.call(ctx, radians);
|
||||
};
|
||||
var translate = ctx.translate;
|
||||
ctx.translate = function(dx,dy){
|
||||
xform = xform.translate(dx,dy);
|
||||
ctx.translate = function (dx, dy) {
|
||||
xform = xform.translate(dx, dy);
|
||||
viewportChanged = true;
|
||||
return translate.call(ctx,dx,dy);
|
||||
return translate.call(ctx, dx, dy);
|
||||
};
|
||||
var transform = ctx.transform;
|
||||
ctx.transform = function(a,b,c,d,e,f){
|
||||
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;
|
||||
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);
|
||||
return transform.call(ctx, a, b, c, d, e, f);
|
||||
};
|
||||
var setTransform = ctx.setTransform;
|
||||
ctx.setTransform = function(a,b,c,d,e,f){
|
||||
ctx.setTransform = function (a, b, c, d, e, f) {
|
||||
xform.a = a;
|
||||
xform.b = b;
|
||||
xform.c = c;
|
||||
@@ -169,109 +204,127 @@ GCODE.renderer = (function(){
|
||||
xform.e = e;
|
||||
xform.f = f;
|
||||
viewportChanged = true;
|
||||
return setTransform.call(ctx,a,b,c,d,e,f);
|
||||
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;
|
||||
var pt = svg.createSVGPoint();
|
||||
ctx.transformedPoint = function (x, y) {
|
||||
pt.x = x;
|
||||
pt.y = y;
|
||||
return pt.matrixTransform(xform.inverse());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
var startCanvas = function() {
|
||||
var startCanvas = function () {
|
||||
var jqueryCanvas = $(renderOptions["container"]);
|
||||
//jqueryCanvas.css("background-color", renderOptions["bgColorOffGrid"]);
|
||||
canvas = jqueryCanvas[0];
|
||||
|
||||
ctx = canvas.getContext('2d');
|
||||
ctx = canvas.getContext("2d");
|
||||
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;
|
||||
lastX = ctxWidth / 2;
|
||||
lastY = ctxHeight / 2;
|
||||
ctx.lineWidth = 2 * lineWidthFactor;
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineCap = "round";
|
||||
trackTransforms(ctx);
|
||||
|
||||
ctx.scale(1,-1); // Invert y-axis
|
||||
ctx.scale(1, -1); // Invert y-axis
|
||||
|
||||
// dragging => translating
|
||||
canvas.addEventListener('mousedown', function(event){
|
||||
document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none';
|
||||
canvas.addEventListener(
|
||||
"mousedown",
|
||||
function (event) {
|
||||
document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect =
|
||||
"none";
|
||||
|
||||
// remember starting point of dragging gesture
|
||||
lastX = (event.offsetX || (event.pageX - canvas.offsetLeft)) * pixelRatio;
|
||||
lastY = (event.offsetY || (event.pageY - canvas.offsetTop)) * pixelRatio;
|
||||
// remember starting point of dragging gesture
|
||||
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);
|
||||
var pt = ctx.transformedPoint(lastX, lastY);
|
||||
if (
|
||||
!renderOptions["onDragStart"] ||
|
||||
renderOptions["onDragStart"](pt) !== false
|
||||
)
|
||||
dragStart = pt;
|
||||
},
|
||||
false
|
||||
);
|
||||
|
||||
canvas.addEventListener('mousemove', function(event){
|
||||
// save current mouse coordinates
|
||||
lastX = (event.offsetX || (event.pageX - canvas.offsetLeft)) * pixelRatio;
|
||||
lastY = (event.offsetY || (event.pageY - canvas.offsetTop)) * pixelRatio;
|
||||
canvas.addEventListener(
|
||||
"mousemove",
|
||||
function (event) {
|
||||
// save current mouse coordinates
|
||||
lastX = (event.offsetX || event.pageX - canvas.offsetLeft) * pixelRatio;
|
||||
lastY = (event.offsetY || event.pageY - canvas.offsetTop) * pixelRatio;
|
||||
|
||||
// mouse movement => dragged
|
||||
if (dragStart !== undefined) {
|
||||
// translate
|
||||
var pt = ctx.transformedPoint(lastX,lastY);
|
||||
// mouse movement => dragged
|
||||
if (dragStart !== undefined) {
|
||||
// translate
|
||||
var pt = ctx.transformedPoint(lastX, lastY);
|
||||
|
||||
if (renderOptions["onDrag"] && (renderOptions["onDrag"](pt) === false))
|
||||
return;
|
||||
if (renderOptions["onDrag"] && renderOptions["onDrag"](pt) === false)
|
||||
return;
|
||||
|
||||
ctx.translate(pt.x - dragStart.x, pt.y - dragStart.y);
|
||||
reRender();
|
||||
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;
|
||||
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
|
||||
});
|
||||
if (renderOptions["onInternalOptionChange"] !== undefined) {
|
||||
renderOptions["onInternalOptionChange"]({
|
||||
centerViewport: false,
|
||||
moveModel: false,
|
||||
zoomInOnModel: false,
|
||||
zoomInOnBed: false
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
},
|
||||
false
|
||||
);
|
||||
|
||||
canvas.addEventListener('mouseup', function(event){
|
||||
// reset dragStart
|
||||
dragStart = undefined;
|
||||
canvas.addEventListener(
|
||||
"mouseup",
|
||||
function (event) {
|
||||
// reset dragStart
|
||||
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);
|
||||
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
|
||||
);
|
||||
|
||||
// mouse wheel => zooming
|
||||
var zoom = function(clicks){
|
||||
var zoom = function (clicks) {
|
||||
// focus on last mouse position prior to zoom
|
||||
var pt = ctx.transformedPoint(lastX, lastY);
|
||||
ctx.translate(pt.x,pt.y);
|
||||
ctx.translate(pt.x, pt.y);
|
||||
|
||||
// determine zooming factor and perform zoom
|
||||
var factor = Math.pow(scaleFactor,clicks);
|
||||
ctx.scale(factor,factor);
|
||||
var factor = Math.pow(scaleFactor, clicks);
|
||||
ctx.scale(factor, factor);
|
||||
|
||||
// return to old position
|
||||
ctx.translate(-pt.x,-pt.y);
|
||||
ctx.translate(-pt.x, -pt.y);
|
||||
|
||||
// render
|
||||
reRender();
|
||||
@@ -293,7 +346,7 @@ GCODE.renderer = (function(){
|
||||
});
|
||||
}
|
||||
};
|
||||
var handleScroll = function(event){
|
||||
var handleScroll = function (event) {
|
||||
var delta;
|
||||
|
||||
// determine zoom direction & delta
|
||||
@@ -306,13 +359,13 @@ GCODE.renderer = (function(){
|
||||
|
||||
return event.preventDefault() && false;
|
||||
};
|
||||
canvas.addEventListener('DOMMouseScroll',handleScroll,false);
|
||||
canvas.addEventListener('mousewheel',handleScroll,false);
|
||||
canvas.addEventListener("DOMMouseScroll", handleScroll, false);
|
||||
canvas.addEventListener("mousewheel", handleScroll, false);
|
||||
};
|
||||
|
||||
var drawGrid = function() {
|
||||
var drawGrid = function () {
|
||||
ctx.translate(offsetBedX, offsetBedY);
|
||||
if(renderOptions["bed"]["circular"]) {
|
||||
if (renderOptions["bed"]["circular"]) {
|
||||
drawCircularGrid();
|
||||
} else {
|
||||
drawRectangularGrid();
|
||||
@@ -320,7 +373,7 @@ GCODE.renderer = (function(){
|
||||
ctx.translate(-offsetBedX, -offsetBedY);
|
||||
};
|
||||
|
||||
var drawRectangularGrid = function() {
|
||||
var drawRectangularGrid = function () {
|
||||
var x, y;
|
||||
var width = renderOptions["bed"]["x"];
|
||||
var height = renderOptions["bed"]["y"];
|
||||
@@ -394,7 +447,7 @@ GCODE.renderer = (function(){
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
var drawCircularGrid = function() {
|
||||
var drawCircularGrid = function () {
|
||||
var i;
|
||||
|
||||
ctx.strokeStyle = renderOptions["colorGrid"];
|
||||
@@ -430,7 +483,7 @@ GCODE.renderer = (function(){
|
||||
ctx.beginPath();
|
||||
for (i = 0; i <= r; i += gridStep) {
|
||||
var x = i;
|
||||
var y = Math.sqrt(r*r - x*x);
|
||||
var y = Math.sqrt(r * r - x * x);
|
||||
|
||||
ctx.moveTo(x, -1 * y);
|
||||
ctx.lineTo(x, y);
|
||||
@@ -447,7 +500,7 @@ GCODE.renderer = (function(){
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
var drawBoundingBox = function() {
|
||||
var drawBoundingBox = function () {
|
||||
if (!modelInfo) return;
|
||||
|
||||
var minX, minY, width, height;
|
||||
@@ -485,7 +538,7 @@ GCODE.renderer = (function(){
|
||||
ctx.setLineDash([1, 0]);
|
||||
};
|
||||
|
||||
var drawTriangle = function(centerX, centerY, length, up) {
|
||||
var drawTriangle = function (centerX, centerY, length, up) {
|
||||
/*
|
||||
* (cx,cy)
|
||||
* * ^
|
||||
@@ -532,8 +585,18 @@ GCODE.renderer = (function(){
|
||||
ctx.lineJoin = origLineJoin;
|
||||
};
|
||||
|
||||
var drawLayer = function(layerNum, fromProgress, toProgress, isNotCurrentLayer){
|
||||
log.trace("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
|
||||
var drawLayer = function (layerNum, fromProgress, toProgress, isNotCurrentLayer) {
|
||||
log.trace(
|
||||
"Drawing layer " +
|
||||
layerNum +
|
||||
" from " +
|
||||
fromProgress +
|
||||
" to " +
|
||||
toProgress +
|
||||
" (current: " +
|
||||
!isNotCurrentLayer +
|
||||
")"
|
||||
);
|
||||
|
||||
var i;
|
||||
|
||||
@@ -560,17 +623,15 @@ GCODE.renderer = (function(){
|
||||
// previous layer exists, use last x/y as prevX/prevY
|
||||
prevX = undefined;
|
||||
prevY = undefined;
|
||||
var prevModelLayer = model[layerNum-1];
|
||||
for (i = prevModelLayer.length-1; i >= 0; i--) {
|
||||
var prevModelLayer = model[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) break;
|
||||
}
|
||||
if (prevY === undefined && prevModelLayer[i].y !== undefined) {
|
||||
prevY = prevModelLayer[i].y;
|
||||
if (prevX !== undefined)
|
||||
break;
|
||||
if (prevX !== undefined) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -586,7 +647,13 @@ GCODE.renderer = (function(){
|
||||
|
||||
// alpha value (100% if current layer is being rendered, 30% otherwise)
|
||||
// Note - If showing currently layer as preview - also render it at 30% and draw the progress over the top at 100%
|
||||
var alpha = (renderOptions['showNextLayer'] || renderOptions['showCurrentLayer'] || renderOptions['showPreviousLayer']) && isNotCurrentLayer ? 0.3 : 1.0;
|
||||
var alpha =
|
||||
(renderOptions["showNextLayer"] ||
|
||||
renderOptions["showCurrentLayer"] ||
|
||||
renderOptions["showPreviousLayer"]) &&
|
||||
isNotCurrentLayer
|
||||
? 0.3
|
||||
: 1.0;
|
||||
|
||||
var colorLine = {};
|
||||
var colorMove = {};
|
||||
@@ -599,7 +666,11 @@ GCODE.renderer = (function(){
|
||||
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();
|
||||
rv = colorLine[tool] = pusher
|
||||
.color(lineColor)
|
||||
.shade(shade)
|
||||
.alpha(alpha)
|
||||
.html();
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
@@ -608,7 +679,11 @@ GCODE.renderer = (function(){
|
||||
var rv = colorMove[tool];
|
||||
if (rv === undefined) {
|
||||
var shade = tool * 0.15;
|
||||
rv = colorMove[tool] = pusher.color(renderOptions["colorMove"]).shade(shade).alpha(alpha).html();
|
||||
rv = colorMove[tool] = pusher
|
||||
.color(renderOptions["colorMove"])
|
||||
.shade(shade)
|
||||
.alpha(alpha)
|
||||
.html();
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
@@ -617,7 +692,11 @@ GCODE.renderer = (function(){
|
||||
var rv = colorRetract[tool];
|
||||
if (rv === undefined) {
|
||||
var shade = tool * 0.15;
|
||||
rv = colorRetract[tool] = pusher.color(renderOptions["colorRetract"]).shade(shade).alpha(alpha).html();
|
||||
rv = colorRetract[tool] = pusher
|
||||
.color(renderOptions["colorRetract"])
|
||||
.shade(shade)
|
||||
.alpha(alpha)
|
||||
.html();
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
@@ -626,14 +705,18 @@ GCODE.renderer = (function(){
|
||||
var rv = colorRestart[tool];
|
||||
if (rv === undefined) {
|
||||
var shade = tool * 0.15;
|
||||
rv = colorRestart[tool] = pusher.color(renderOptions["colorRestart"]).shade(shade).alpha(alpha).html();
|
||||
rv = colorRestart[tool] = pusher
|
||||
.color(renderOptions["colorRestart"])
|
||||
.shade(shade)
|
||||
.alpha(alpha)
|
||||
.html();
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
var prevPathType = "fill";
|
||||
function strokePathIfNeeded(newPathType, strokeStyle) {
|
||||
if ((newPathType != prevPathType) || (newPathType == "fill")) {
|
||||
if (newPathType != prevPathType || newPathType == "fill") {
|
||||
if (prevPathType != "fill") {
|
||||
ctx.stroke();
|
||||
}
|
||||
@@ -641,8 +724,8 @@ GCODE.renderer = (function(){
|
||||
|
||||
ctx.beginPath();
|
||||
if (newPathType != "fill") {
|
||||
ctx.strokeStyle = strokeStyle;
|
||||
ctx.moveTo(prevX, prevY);
|
||||
ctx.strokeStyle = strokeStyle;
|
||||
ctx.moveTo(prevX, prevY);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -650,7 +733,7 @@ GCODE.renderer = (function(){
|
||||
ctx.lineJoin = "round";
|
||||
|
||||
for (i = fromProgress; i <= toProgress; i++) {
|
||||
if (typeof(cmds[i]) === 'undefined') continue;
|
||||
if (typeof cmds[i] === "undefined") continue;
|
||||
var cmd = cmds[i];
|
||||
|
||||
if (cmd.prevX !== undefined && cmd.prevY !== undefined) {
|
||||
@@ -689,27 +772,34 @@ GCODE.renderer = (function(){
|
||||
}
|
||||
|
||||
strokePathIfNeeded("move", getColorMoveForTool(tool));
|
||||
if(renderOptions["showMoves"] && !isNotCurrentLayer) {
|
||||
if (renderOptions["showMoves"] && !isNotCurrentLayer) {
|
||||
// move => draw line from (prevX, prevY) to (x, y) in move color
|
||||
ctx.lineWidth = lineWidthFactor;
|
||||
ctx.lineTo(x,y);
|
||||
ctx.lineTo(x, y);
|
||||
}
|
||||
} else if(cmd.extrude) {
|
||||
} else if (cmd.extrude) {
|
||||
if (cmd.retract == 0) {
|
||||
// no retraction => real extrusion move, use tool color to draw line
|
||||
strokePathIfNeeded("extrude", getColorLineForTool(tool));
|
||||
ctx.lineWidth = renderOptions['extrusionWidth'] * lineWidthFactor;
|
||||
if (cmd.direction !== undefined && cmd.direction != 0){
|
||||
ctx.lineWidth = renderOptions["extrusionWidth"] * lineWidthFactor;
|
||||
if (cmd.direction !== undefined && cmd.direction != 0) {
|
||||
var di = cmd.i;
|
||||
var dj = cmd.j;
|
||||
var centerX = prevX+di;
|
||||
var centerY = prevY+dj;
|
||||
var startAngle = Math.atan2(prevY-centerY, prevX - centerX);
|
||||
var centerX = prevX + di;
|
||||
var centerY = prevY + dj;
|
||||
var startAngle = Math.atan2(prevY - centerY, prevX - centerX);
|
||||
var endAngle = Math.atan2(y - centerY, x - centerX);
|
||||
var radius=Math.sqrt(di*di+dj*dj);
|
||||
ctx.arc(centerX,centerY,radius,startAngle,endAngle,cmd.direction<0); // Y-axis is inverted so direction is also inverted
|
||||
var radius = Math.sqrt(di * di + dj * dj);
|
||||
ctx.arc(
|
||||
centerX,
|
||||
centerY,
|
||||
radius,
|
||||
startAngle,
|
||||
endAngle,
|
||||
cmd.direction < 0
|
||||
); // Y-axis is inverted so direction is also inverted
|
||||
} else {
|
||||
ctx.lineTo(x,y);
|
||||
ctx.lineTo(x, y);
|
||||
}
|
||||
} else {
|
||||
// we were previously retracting, now we are restarting => draw dot if configured to do so
|
||||
@@ -732,16 +822,21 @@ GCODE.renderer = (function(){
|
||||
}
|
||||
|
||||
if (renderOptions["showHead"] && !isNotCurrentLayer) {
|
||||
var sizeHeadSpot = renderOptions["sizeHeadSpot"] * lineWidthFactor + lineWidthFactor / 2;
|
||||
var sizeHeadSpot =
|
||||
renderOptions["sizeHeadSpot"] * lineWidthFactor + lineWidthFactor / 2;
|
||||
var shade = tool * 0.15;
|
||||
ctx.fillStyle = pusher.color(renderOptions["colorHead"]).shade(shade).alpha(alpha).html();
|
||||
ctx.fillStyle = pusher
|
||||
.color(renderOptions["colorHead"])
|
||||
.shade(shade)
|
||||
.alpha(alpha)
|
||||
.html();
|
||||
ctx.beginPath();
|
||||
ctx.arc(prevX, prevY, sizeHeadSpot, 0, Math.PI*2, true);
|
||||
ctx.arc(prevX, prevY, sizeHeadSpot, 0, Math.PI * 2, true);
|
||||
ctx.fill();
|
||||
}
|
||||
};
|
||||
|
||||
var applyOffsets = function() {
|
||||
var applyOffsets = function () {
|
||||
var canvasCenter;
|
||||
|
||||
// determine bed and model offsets
|
||||
@@ -749,8 +844,12 @@ GCODE.renderer = (function(){
|
||||
if (renderOptions["centerViewport"] || renderOptions["zoomInOnModel"]) {
|
||||
canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
|
||||
if (modelInfo) {
|
||||
offsetModelX = canvasCenter.x - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2;
|
||||
offsetModelY = canvasCenter.y - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2;
|
||||
offsetModelX =
|
||||
canvasCenter.x -
|
||||
(modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2;
|
||||
offsetModelY =
|
||||
canvasCenter.y -
|
||||
(modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2;
|
||||
} else {
|
||||
offsetModelX = 0;
|
||||
offsetModelY = 0;
|
||||
@@ -758,11 +857,24 @@ GCODE.renderer = (function(){
|
||||
offsetBedX = 0;
|
||||
offsetBedY = 0;
|
||||
} else if (modelInfo && renderOptions["moveModel"]) {
|
||||
offsetModelX = (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2);
|
||||
offsetModelY = (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2);
|
||||
offsetBedX = -1 * (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2);
|
||||
offsetBedY = -1 * (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2);
|
||||
} else if (renderOptions["bed"]["circular"] || renderOptions["bed"]["centeredOrigin"]) {
|
||||
offsetModelX =
|
||||
renderOptions["bed"]["x"] / 2 -
|
||||
(modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2;
|
||||
offsetModelY =
|
||||
renderOptions["bed"]["y"] / 2 -
|
||||
(modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2;
|
||||
offsetBedX =
|
||||
-1 *
|
||||
(renderOptions["bed"]["x"] / 2 -
|
||||
(modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2);
|
||||
offsetBedY =
|
||||
-1 *
|
||||
(renderOptions["bed"]["y"] / 2 -
|
||||
(modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2);
|
||||
} else if (
|
||||
renderOptions["bed"]["circular"] ||
|
||||
renderOptions["bed"]["centeredOrigin"]
|
||||
) {
|
||||
canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
|
||||
offsetModelX = canvasCenter.x;
|
||||
offsetModelY = canvasCenter.y;
|
||||
@@ -777,9 +889,9 @@ GCODE.renderer = (function(){
|
||||
if (ctx) ctx.translate(offsetModelX, offsetModelY);
|
||||
};
|
||||
|
||||
var applyZoom = function() {
|
||||
var applyZoom = function () {
|
||||
// get middle of canvas
|
||||
var pt = ctx.transformedPoint(canvas.width/2,canvas.height/2);
|
||||
var pt = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
|
||||
|
||||
// get current transform
|
||||
var transform = ctx.getTransform();
|
||||
@@ -797,11 +909,16 @@ GCODE.renderer = (function(){
|
||||
var width = modelInfo.boundingBox.maxX - modelInfo.boundingBox.minX;
|
||||
var length = modelInfo.boundingBox.maxY - modelInfo.boundingBox.minY;
|
||||
|
||||
var scaleF = width > length ? (canvas.width - 10) / width : (canvas.height - 10) / length;
|
||||
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);
|
||||
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);
|
||||
}
|
||||
@@ -812,7 +929,7 @@ GCODE.renderer = (function(){
|
||||
}
|
||||
};
|
||||
|
||||
var applyInversion = function() {
|
||||
var applyInversion = function () {
|
||||
var width = canvas.width - 10;
|
||||
var height = canvas.height - 10;
|
||||
|
||||
@@ -837,19 +954,22 @@ GCODE.renderer = (function(){
|
||||
currentInvertY = invertY;
|
||||
};
|
||||
|
||||
// ***** PUBLIC *******
|
||||
// ***** PUBLIC *******
|
||||
return {
|
||||
init: function(){
|
||||
init: function () {
|
||||
startCanvas();
|
||||
initialized = true;
|
||||
var bedWidth = renderOptions["bed"]["x"];
|
||||
var bedHeight = renderOptions["bed"]["y"];
|
||||
if(renderOptions["bed"]["circular"]) {
|
||||
if (renderOptions["bed"]["circular"]) {
|
||||
bedWidth = bedHeight = renderOptions["bed"]["r"] * 2;
|
||||
}
|
||||
|
||||
// Ratio of bed to canvas viewport
|
||||
var viewportRatio = Math.min((canvas.width - 10) / bedWidth, (canvas.height - 10) / bedHeight);
|
||||
var viewportRatio = Math.min(
|
||||
(canvas.width - 10) / bedWidth,
|
||||
(canvas.height - 10) / bedHeight
|
||||
);
|
||||
|
||||
// Apply initial translation to center the bed in the viewport
|
||||
var translationX, translationY;
|
||||
@@ -858,7 +978,9 @@ GCODE.renderer = (function(){
|
||||
translationY = canvas.height / 2;
|
||||
} else {
|
||||
translationX = (canvas.width - bedWidth * viewportRatio) / 2;
|
||||
translationY = bedHeight * viewportRatio + (canvas.height - bedHeight * viewportRatio) / 2;
|
||||
translationY =
|
||||
bedHeight * viewportRatio +
|
||||
(canvas.height - bedHeight * viewportRatio) / 2;
|
||||
}
|
||||
ctx.translate(translationX, -translationY);
|
||||
|
||||
@@ -872,23 +994,33 @@ GCODE.renderer = (function(){
|
||||
// Scaling to apply to move lines and extrusion/retraction markers
|
||||
lineWidthFactor = 1 / viewportRatio;
|
||||
},
|
||||
setOption: function(options){
|
||||
setOption: function (options) {
|
||||
var mustRefresh = false;
|
||||
var dirty = false;
|
||||
for (var opt in options) {
|
||||
if (!renderOptions.hasOwnProperty(opt) || !options.hasOwnProperty(opt)) continue;
|
||||
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"]) > -1) {
|
||||
if (
|
||||
$.inArray(opt, [
|
||||
"moveModel",
|
||||
"centerViewport",
|
||||
"zoomInOnModel",
|
||||
"bed",
|
||||
"invertAxes",
|
||||
"onViewportChange"
|
||||
]) > -1
|
||||
) {
|
||||
mustRefresh = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!dirty) return;
|
||||
if(initialized) {
|
||||
if (initialized) {
|
||||
if (mustRefresh) {
|
||||
this.refresh();
|
||||
} else {
|
||||
@@ -896,13 +1028,13 @@ GCODE.renderer = (function(){
|
||||
}
|
||||
}
|
||||
},
|
||||
getOptions: function(){
|
||||
getOptions: function () {
|
||||
return renderOptions;
|
||||
},
|
||||
debugGetModel: function(){
|
||||
debugGetModel: function () {
|
||||
return model;
|
||||
},
|
||||
render: function(layerNum, fromProgress, toProgress){
|
||||
render: function (layerNum, fromProgress, toProgress) {
|
||||
if (!initialized) this.init();
|
||||
|
||||
layerNumStore = layerNum;
|
||||
@@ -911,17 +1043,17 @@ GCODE.renderer = (function(){
|
||||
|
||||
reRender();
|
||||
},
|
||||
getModelNumLayers: function(){
|
||||
getModelNumLayers: function () {
|
||||
return model ? model.length : 1;
|
||||
},
|
||||
getLayerNumSegments: function(layer){
|
||||
if(model){
|
||||
return model[layer]?model[layer].length:1;
|
||||
}else{
|
||||
getLayerNumSegments: function (layer) {
|
||||
if (model) {
|
||||
return model[layer] ? model[layer].length : 1;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
},
|
||||
clear: function() {
|
||||
clear: function () {
|
||||
offsetModelX = 0;
|
||||
offsetModelY = 0;
|
||||
offsetBedX = 0;
|
||||
@@ -934,7 +1066,7 @@ GCODE.renderer = (function(){
|
||||
|
||||
this.doRender([], 0);
|
||||
},
|
||||
doRender: function(mdl, layerNum){
|
||||
doRender: function (mdl, layerNum) {
|
||||
model = mdl;
|
||||
modelInfo = undefined;
|
||||
|
||||
@@ -958,20 +1090,19 @@ GCODE.renderer = (function(){
|
||||
|
||||
this.render(layerNum, 0, toProgress);
|
||||
},
|
||||
refresh: function(layerNum) {
|
||||
refresh: function (layerNum) {
|
||||
if (layerNum === undefined) layerNum = layerNumStore;
|
||||
this.doRender(model, layerNum);
|
||||
},
|
||||
getZ: function(layerNum){
|
||||
if(!model || !model[layerNum]){
|
||||
return '-1';
|
||||
getZ: function (layerNum) {
|
||||
if (!model || !model[layerNum]) {
|
||||
return "-1";
|
||||
}
|
||||
var cmds = model[layerNum];
|
||||
for(var i = 0; i < cmds.length; i++){
|
||||
if(cmds[i].prevZ !== undefined) return cmds[i].prevZ;
|
||||
for (var i = 0; i < cmds.length; i++) {
|
||||
if (cmds[i].prevZ !== undefined) return cmds[i].prevZ;
|
||||
}
|
||||
return '-1';
|
||||
return "-1";
|
||||
}
|
||||
|
||||
}
|
||||
}());
|
||||
};
|
||||
})();
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
var GCODE = {};
|
||||
|
||||
GCODE.ui = (function(){
|
||||
GCODE.ui = (function () {
|
||||
var uiOptions = {
|
||||
container: undefined,
|
||||
toolOffsets: undefined,
|
||||
@@ -16,13 +16,13 @@ GCODE.ui = (function(){
|
||||
onLayerSelected: undefined
|
||||
};
|
||||
|
||||
var setProgress = function(type, progress) {
|
||||
var setProgress = function (type, progress) {
|
||||
if (uiOptions["onProgress"]) {
|
||||
uiOptions.onProgress(type, progress);
|
||||
}
|
||||
};
|
||||
|
||||
var switchLayer = function(layerNum, onlyInfo) {
|
||||
var switchLayer = function (layerNum, onlyInfo) {
|
||||
if (!onlyInfo) {
|
||||
var segmentCount = GCODE.renderer.getLayerNumSegments(layerNum);
|
||||
GCODE.renderer.render(layerNum, 0, segmentCount - 1);
|
||||
@@ -41,17 +41,17 @@ GCODE.ui = (function(){
|
||||
}
|
||||
};
|
||||
|
||||
var switchCommands = function(layerNum, first, last) {
|
||||
var switchCommands = function (layerNum, first, last) {
|
||||
GCODE.renderer.render(layerNum, first, last);
|
||||
};
|
||||
|
||||
var processMessage = function(e){
|
||||
var processMessage = function (e) {
|
||||
var data = e.data;
|
||||
switch (data.cmd) {
|
||||
case "returnModel":
|
||||
GCODE.ui.worker.postMessage({
|
||||
"cmd":"analyzeModel",
|
||||
"msg":{}
|
||||
cmd: "analyzeModel",
|
||||
msg: {}
|
||||
});
|
||||
break;
|
||||
|
||||
@@ -93,34 +93,36 @@ GCODE.ui = (function(){
|
||||
}
|
||||
};
|
||||
|
||||
var checkCapabilities = function(){
|
||||
var checkCapabilities = function () {
|
||||
var warnings = [];
|
||||
var fatal = [];
|
||||
|
||||
var errorList = document.getElementById("errorList");
|
||||
if(fatal.length>0){
|
||||
if (fatal.length > 0) {
|
||||
if (errorList) {
|
||||
errorList.innerHTML = '<ul>' + fatal.join('') + '</ul>';
|
||||
errorList.innerHTML = "<ul>" + fatal.join("") + "</ul>";
|
||||
}
|
||||
console.log("Initialization failed: unsupported browser.")
|
||||
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>");
|
||||
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 (warnings.length > 0) {
|
||||
if (errorList) {
|
||||
errorList.innerHTML = '<ul>' + warnings.join('') + '</ul>';
|
||||
errorList.innerHTML = "<ul>" + warnings.join("") + "</ul>";
|
||||
}
|
||||
console.log("Initialization succeeded with warnings.", warnings);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
var setOptions = function(options) {
|
||||
var setOptions = function (options) {
|
||||
if (!options) return;
|
||||
for (var opt in options) {
|
||||
if (options[opt] === undefined) continue;
|
||||
@@ -132,7 +134,7 @@ GCODE.ui = (function(){
|
||||
|
||||
return {
|
||||
worker: undefined,
|
||||
init: function(options){
|
||||
init: function (options) {
|
||||
if (options) setOptions(options);
|
||||
if (!options.container) {
|
||||
return false;
|
||||
@@ -146,7 +148,7 @@ GCODE.ui = (function(){
|
||||
setProgress("", 0);
|
||||
|
||||
this.worker = new Worker(GCODE_WORKER);
|
||||
this.worker.addEventListener('message', processMessage, false);
|
||||
this.worker.addEventListener("message", processMessage, false);
|
||||
|
||||
GCODE.renderer.setOption({
|
||||
container: options.container,
|
||||
@@ -161,7 +163,7 @@ GCODE.ui = (function(){
|
||||
return true;
|
||||
},
|
||||
|
||||
clear: function() {
|
||||
clear: function () {
|
||||
GCODE.gCodeReader.clear();
|
||||
GCODE.renderer.clear();
|
||||
|
||||
@@ -174,11 +176,11 @@ GCODE.ui = (function(){
|
||||
}
|
||||
},
|
||||
|
||||
updateLayerInfo: function(layerNum){
|
||||
updateLayerInfo: function (layerNum) {
|
||||
switchLayer(layerNum, true);
|
||||
},
|
||||
|
||||
updateOptions: function(options) {
|
||||
updateOptions: function (options) {
|
||||
setOptions(options.ui);
|
||||
if (options.reader) {
|
||||
GCODE.gCodeReader.setOption(options.reader);
|
||||
@@ -188,12 +190,12 @@ GCODE.ui = (function(){
|
||||
}
|
||||
},
|
||||
|
||||
changeSelectedLayer: function(newLayerNum) {
|
||||
changeSelectedLayer: function (newLayerNum) {
|
||||
switchLayer(newLayerNum);
|
||||
},
|
||||
|
||||
changeSelectedCommands: function(layerNum, first, last) {
|
||||
changeSelectedCommands: function (layerNum, first, last) {
|
||||
switchCommands(layerNum, first, last);
|
||||
}
|
||||
}
|
||||
}());
|
||||
};
|
||||
})();
|
||||
@@ -6,17 +6,28 @@
|
||||
|
||||
var gcode;
|
||||
var firstReport;
|
||||
var toolOffsets = [
|
||||
{x: 0, y: 0}
|
||||
];
|
||||
var toolOffsets = [{x: 0, y: 0}];
|
||||
var g90InfluencesExtruder = false;
|
||||
var z_heights = {};
|
||||
var model = [];
|
||||
var max = {x: undefined, y: undefined, z: undefined};
|
||||
var min = {x: undefined, y: undefined, z: undefined};
|
||||
var boundingBox = {minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, minZ: undefined, maxZ: undefined};
|
||||
var boundingBox = {
|
||||
minX: undefined,
|
||||
maxX: undefined,
|
||||
minY: undefined,
|
||||
maxY: undefined,
|
||||
minZ: undefined,
|
||||
maxZ: undefined
|
||||
};
|
||||
var modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
var bed = {x: undefined, y: undefined, r: undefined, circular: false, centeredOrigin: false};
|
||||
var bed = {
|
||||
x: undefined,
|
||||
y: undefined,
|
||||
r: undefined,
|
||||
circular: false,
|
||||
centeredOrigin: false
|
||||
};
|
||||
var ignoreOutsideBed = false;
|
||||
var filamentByLayer = {};
|
||||
var totalFilament = [0];
|
||||
@@ -29,8 +40,8 @@ var speedsByLayer = {extrude: {}, retract: {}, move: {}};
|
||||
|
||||
var sendLayerToParent = function (layerNum, z, progress) {
|
||||
self.postMessage({
|
||||
"cmd": "returnLayer",
|
||||
"msg": {
|
||||
cmd: "returnLayer",
|
||||
msg: {
|
||||
cmds: model[layerNum],
|
||||
layerNum: layerNum,
|
||||
zHeightObject: {zValue: z, layer: z_heights[z]},
|
||||
@@ -50,8 +61,8 @@ var sendMultiLayerToParent = function (layerNum, z, progress) {
|
||||
}
|
||||
|
||||
self.postMessage({
|
||||
"cmd": "returnMultiLayer",
|
||||
"msg": {
|
||||
cmd: "returnMultiLayer",
|
||||
msg: {
|
||||
model: tmpModel,
|
||||
layerNum: layerNum,
|
||||
zHeightObject: {zValue: z, layer: tmpZHeight},
|
||||
@@ -61,11 +72,10 @@ var sendMultiLayerToParent = function (layerNum, z, progress) {
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
var sendSizeProgress = function (progress) {
|
||||
self.postMessage({
|
||||
"cmd": "analyzeProgress",
|
||||
"msg": {
|
||||
cmd: "analyzeProgress",
|
||||
msg: {
|
||||
progress: progress,
|
||||
printTime: printTime
|
||||
}
|
||||
@@ -74,8 +84,8 @@ var sendSizeProgress = function (progress) {
|
||||
|
||||
var sendAnalyzeDone = function () {
|
||||
self.postMessage({
|
||||
"cmd": "analyzeDone",
|
||||
"msg": {
|
||||
cmd: "analyzeDone",
|
||||
msg: {
|
||||
max: max,
|
||||
min: min,
|
||||
modelSize: modelSize,
|
||||
@@ -101,7 +111,7 @@ var purgeLayers = function () {
|
||||
purge = true;
|
||||
} else {
|
||||
for (var j = 0; j < model[i].length; j++) {
|
||||
if (model[i][j].extrude)purge = false;
|
||||
if (model[i][j].extrude) purge = false;
|
||||
}
|
||||
}
|
||||
if (!purge) {
|
||||
@@ -110,7 +120,7 @@ var purgeLayers = function () {
|
||||
}
|
||||
};
|
||||
|
||||
var bedBounds = function() {
|
||||
var bedBounds = function () {
|
||||
if (!bed) {
|
||||
return {xMin: 0, xMax: 0, yMin: 0, yMax: 0};
|
||||
}
|
||||
@@ -119,30 +129,36 @@ var bedBounds = function() {
|
||||
if (bed.circular) {
|
||||
result = {xMin: -bed.r, xMax: bed.r, yMin: -bed.r, yMax: bed.r};
|
||||
} else if (bed.centeredOrigin) {
|
||||
result = {xMin: -bed.x/2.0, xMax: bed.x/2.0, yMin: -bed.y/2.0, yMax: bed.y/2.0};
|
||||
result = {
|
||||
xMin: -bed.x / 2.0,
|
||||
xMax: bed.x / 2.0,
|
||||
yMin: -bed.y / 2.0,
|
||||
yMax: bed.y / 2.0
|
||||
};
|
||||
} else {
|
||||
result = {xMin: 0, xMax: bed.x, yMin: 0, yMax: bed.y};
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
var withinBedBounds = function(x, y, bedBounds) {
|
||||
var withinBedBounds = function (x, y, bedBounds) {
|
||||
if (!ignoreOutsideBed) return true;
|
||||
|
||||
var result = true;
|
||||
|
||||
if (x !== undefined && !isNaN(x)) {
|
||||
result = result && (x >= bedBounds.xMin && x <= bedBounds.xMax);
|
||||
result = result && x >= bedBounds.xMin && x <= bedBounds.xMax;
|
||||
}
|
||||
if (y !== undefined && !isNaN(y)) {
|
||||
result = result && (y >= bedBounds.yMin && y <= bedBounds.yMax);
|
||||
result = result && y >= bedBounds.yMin && y <= bedBounds.yMax;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
var analyzeModel = function () {
|
||||
var tmp1 = 0, tmp2 = 0;
|
||||
var tmp1 = 0,
|
||||
tmp2 = 0;
|
||||
var speedIndex = 0;
|
||||
var type;
|
||||
var printTimeAdd = 0;
|
||||
@@ -158,38 +174,55 @@ var analyzeModel = function () {
|
||||
|
||||
var retract = cmds[j].retract && cmds[j].retract > 0;
|
||||
var extrude = cmds[j].extrude && cmds[j].extrude > 0 && !retract;
|
||||
var move = cmds[j].x !== undefined || cmds[j].y !== undefined || cmds[j].z !== undefined;
|
||||
var move =
|
||||
cmds[j].x !== undefined ||
|
||||
cmds[j].y !== undefined ||
|
||||
cmds[j].z !== undefined;
|
||||
|
||||
var prevInBounds = withinBedBounds(cmds[j].prevX, cmds[j].prevY, bounds);
|
||||
var inBounds = withinBedBounds(cmds[j].x === undefined ? cmds[j].prevX : cmds[j].x,
|
||||
cmds[j].y === undefined ? cmds[j].prevY : cmds[j].y,
|
||||
bounds);
|
||||
var inBounds = withinBedBounds(
|
||||
cmds[j].x === undefined ? cmds[j].prevX : cmds[j].x,
|
||||
cmds[j].y === undefined ? cmds[j].prevY : cmds[j].y,
|
||||
bounds
|
||||
);
|
||||
|
||||
var recordX = function(x, inBounds) {
|
||||
var recordX = function (x, inBounds) {
|
||||
if (x === undefined || isNaN(x)) return;
|
||||
|
||||
max.x = max.x !== undefined ? Math.max(max.x, x) : x;
|
||||
min.x = min.x !== undefined ? Math.min(min.x, x) : x;
|
||||
|
||||
if (inBounds) {
|
||||
boundingBox.minX = boundingBox.minX !== undefined ? Math.min(boundingBox.minX, x): x;
|
||||
boundingBox.maxX = boundingBox.maxX !== undefined ? Math.max(boundingBox.maxX, x): x;
|
||||
boundingBox.minX =
|
||||
boundingBox.minX !== undefined
|
||||
? Math.min(boundingBox.minX, x)
|
||||
: x;
|
||||
boundingBox.maxX =
|
||||
boundingBox.maxX !== undefined
|
||||
? Math.max(boundingBox.maxX, x)
|
||||
: x;
|
||||
}
|
||||
};
|
||||
|
||||
var recordY = function(y, inBounds) {
|
||||
var recordY = function (y, inBounds) {
|
||||
if (y === undefined || isNaN(y)) return;
|
||||
|
||||
max.y = max.y !== undefined ? Math.max(max.y, y) : y;
|
||||
min.y = min.y !== undefined ? Math.min(min.y, y) : y;
|
||||
|
||||
if (inBounds) {
|
||||
boundingBox.minY = boundingBox.minY !== undefined ? Math.min(boundingBox.minY, y): y;
|
||||
boundingBox.maxY = boundingBox.maxY !== undefined ? Math.max(boundingBox.maxY, y): y;
|
||||
boundingBox.minY =
|
||||
boundingBox.minY !== undefined
|
||||
? Math.min(boundingBox.minY, y)
|
||||
: y;
|
||||
boundingBox.maxY =
|
||||
boundingBox.maxY !== undefined
|
||||
? Math.max(boundingBox.maxY, y)
|
||||
: y;
|
||||
}
|
||||
};
|
||||
|
||||
var recordZ = function(z) {
|
||||
var recordZ = function (z) {
|
||||
if (z === undefined || isNaN(z)) return;
|
||||
|
||||
max.z = max.z !== undefined ? Math.max(max.z, z) : z;
|
||||
@@ -210,20 +243,27 @@ var analyzeModel = function () {
|
||||
|
||||
if (!totalFilament[tool]) totalFilament[tool] = 0;
|
||||
if (!filamentByLayer[cmds[j].prevZ]) filamentByLayer[cmds[j].prevZ] = [0];
|
||||
if (!filamentByLayer[cmds[j].prevZ][tool]) filamentByLayer[cmds[j].prevZ][tool] = 0;
|
||||
if (!filamentByLayer[cmds[j].prevZ][tool])
|
||||
filamentByLayer[cmds[j].prevZ][tool] = 0;
|
||||
if (cmds[j].extrusion) {
|
||||
totalFilament[tool] += cmds[j].extrusion;
|
||||
filamentByLayer[cmds[j].prevZ][tool] += cmds[j].extrusion;
|
||||
}
|
||||
|
||||
if (cmds[j].x !== undefined && !isNaN(cmds[j].x)
|
||||
&& cmds[j].y !== undefined && !isNaN(cmds[j].y)) {
|
||||
if (
|
||||
cmds[j].x !== undefined &&
|
||||
!isNaN(cmds[j].x) &&
|
||||
cmds[j].y !== undefined &&
|
||||
!isNaN(cmds[j].y)
|
||||
) {
|
||||
var diffX = cmds[j].x - cmds[j].prevX;
|
||||
var diffY = cmds[j].y - cmds[j].prevY;
|
||||
if (move) {
|
||||
printTimeAdd = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
printTimeAdd =
|
||||
Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
} else if (extrude) {
|
||||
tmp1 = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
tmp1 =
|
||||
Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
tmp2 = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
|
||||
printTimeAdd = Math.max(tmp1, tmp2);
|
||||
} else if (retract) {
|
||||
@@ -240,14 +280,14 @@ var analyzeModel = function () {
|
||||
printTimeByLayer[cmds[j].prevZ] += printTimeAdd;
|
||||
|
||||
if (cmds[j].extrude && cmds[j].retract === 0) {
|
||||
type = 'extrude';
|
||||
type = "extrude";
|
||||
} else if (cmds[j].retract !== 0) {
|
||||
type = 'retract';
|
||||
type = "retract";
|
||||
} else if (!cmds[j].extrude && cmds[j].retract === 0) {
|
||||
type = 'move';
|
||||
type = "move";
|
||||
} else {
|
||||
self.postMessage({cmd: 'unknown type of move'});
|
||||
type = 'unknown';
|
||||
self.postMessage({cmd: "unknown type of move"});
|
||||
type = "unknown";
|
||||
}
|
||||
|
||||
speedIndex = speeds[type].indexOf(cmds[j].speed);
|
||||
@@ -255,16 +295,14 @@ var analyzeModel = function () {
|
||||
speeds[type].push(cmds[j].speed);
|
||||
speedIndex = speeds[type].indexOf(cmds[j].speed);
|
||||
}
|
||||
if (typeof(speedsByLayer[type][cmds[j].prevZ]) === 'undefined') {
|
||||
if (typeof speedsByLayer[type][cmds[j].prevZ] === "undefined") {
|
||||
speedsByLayer[type][cmds[j].prevZ] = [];
|
||||
}
|
||||
if (speedsByLayer[type][cmds[j].prevZ].indexOf(cmds[j].speed) === -1) {
|
||||
speedsByLayer[type][cmds[j].prevZ][speedIndex] = cmds[j].speed;
|
||||
}
|
||||
|
||||
}
|
||||
sendSizeProgress(i / model.length * 100);
|
||||
|
||||
sendSizeProgress((i / model.length) * 100);
|
||||
}
|
||||
purgeLayers();
|
||||
|
||||
@@ -285,11 +323,18 @@ var doParse = function () {
|
||||
var lastSend = 0;
|
||||
|
||||
var layer = 0;
|
||||
var x, y, z = 0;
|
||||
var x,
|
||||
y,
|
||||
z = 0;
|
||||
var center_i, center_j, direction;
|
||||
var prevX = 0, prevY = 0, prevZ = 0;
|
||||
var f, lastF = 4000;
|
||||
var extrude = false, relativeE = false, retract = 0;
|
||||
var prevX = 0,
|
||||
prevY = 0,
|
||||
prevZ = 0;
|
||||
var f,
|
||||
lastF = 4000;
|
||||
var extrude = false,
|
||||
relativeE = false,
|
||||
retract = 0;
|
||||
var relativeMode = false;
|
||||
var zLift = false;
|
||||
var zLiftZ = undefined;
|
||||
@@ -339,8 +384,8 @@ var doParse = function () {
|
||||
args = line.split(/\s/);
|
||||
|
||||
for (j = 0; j < args.length; j++) {
|
||||
switch (argChar = args[j].charAt(0).toLowerCase()) {
|
||||
case 'x':
|
||||
switch ((argChar = args[j].charAt(0).toLowerCase())) {
|
||||
case "x":
|
||||
if (relativeMode) {
|
||||
x = prevX + Number(args[j].slice(1)) + activeToolOffset.x;
|
||||
} else {
|
||||
@@ -349,7 +394,7 @@ var doParse = function () {
|
||||
|
||||
break;
|
||||
|
||||
case 'y':
|
||||
case "y":
|
||||
if (relativeMode) {
|
||||
y = prevY + Number(args[j].slice(1)) + activeToolOffset.y;
|
||||
} else {
|
||||
@@ -358,7 +403,7 @@ var doParse = function () {
|
||||
|
||||
break;
|
||||
|
||||
case 'z':
|
||||
case "z":
|
||||
if (relativeMode) {
|
||||
z = prevZ + Number(args[j].slice(1));
|
||||
} else {
|
||||
@@ -367,10 +412,10 @@ var doParse = function () {
|
||||
|
||||
break;
|
||||
|
||||
case 'e':
|
||||
case 'a':
|
||||
case 'b':
|
||||
case 'c':
|
||||
case "e":
|
||||
case "a":
|
||||
case "b":
|
||||
case "c":
|
||||
assumeNonDC = true;
|
||||
numSlice = Number(args[j].slice(1));
|
||||
|
||||
@@ -379,7 +424,8 @@ var doParse = function () {
|
||||
prev_extrude[tool][argChar] += numSlice;
|
||||
} else {
|
||||
// absolute extrusion positioning
|
||||
prev_extrude[tool]["abs"] = numSlice - prev_extrude[tool][argChar];
|
||||
prev_extrude[tool]["abs"] =
|
||||
numSlice - prev_extrude[tool][argChar];
|
||||
prev_extrude[tool][argChar] = numSlice;
|
||||
}
|
||||
|
||||
@@ -389,7 +435,10 @@ var doParse = function () {
|
||||
retract = -1;
|
||||
} else if (prev_extrude[tool]["abs"] === 0) {
|
||||
retract = 0;
|
||||
} else if (prev_extrude[tool]["abs"] > 0 && prev_retract[tool] < 0) {
|
||||
} else if (
|
||||
prev_extrude[tool]["abs"] > 0 &&
|
||||
prev_retract[tool] < 0
|
||||
) {
|
||||
prev_retract[tool] = 0;
|
||||
retract = 1;
|
||||
} else {
|
||||
@@ -398,31 +447,36 @@ var doParse = function () {
|
||||
|
||||
break;
|
||||
|
||||
case 'f':
|
||||
case "f":
|
||||
numSlice = parseFloat(args[j].slice(1));
|
||||
lastF = numSlice;
|
||||
break;
|
||||
case 'i':
|
||||
case "i":
|
||||
center_i = Number(args[j].slice(1));
|
||||
break;
|
||||
case 'j':
|
||||
case "j":
|
||||
center_j = Number(args[j].slice(1));
|
||||
break;
|
||||
case 'g':
|
||||
if(args[j].charAt(1).toLowerCase() === '2')
|
||||
direction=-1;
|
||||
if(args[j].charAt(1).toLowerCase() === '3')
|
||||
direction=1;
|
||||
case "g":
|
||||
if (args[j].charAt(1).toLowerCase() === "2") direction = -1;
|
||||
if (args[j].charAt(1).toLowerCase() === "3") direction = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (dcExtrude && !assumeNonDC) {
|
||||
extrude = true;
|
||||
prev_extrude[tool]["abs"] = Math.sqrt((prevX - x) * (prevX - x) + (prevY - y) * (prevY - y));
|
||||
prev_extrude[tool]["abs"] = Math.sqrt(
|
||||
(prevX - x) * (prevX - x) + (prevY - y) * (prevY - y)
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
|
||||
if (
|
||||
typeof x !== "undefined" ||
|
||||
typeof y !== "undefined" ||
|
||||
typeof z !== "undefined" ||
|
||||
retract !== 0
|
||||
) {
|
||||
addToModel = true;
|
||||
move = true;
|
||||
}
|
||||
@@ -460,24 +514,24 @@ var doParse = function () {
|
||||
prev_extrude[tool]["b"] = 0;
|
||||
prev_extrude[tool]["c"] = 0;
|
||||
} else {
|
||||
switch (argChar = args[j].charAt(0).toLowerCase()) {
|
||||
case 'x':
|
||||
switch ((argChar = args[j].charAt(0).toLowerCase())) {
|
||||
case "x":
|
||||
x = Number(args[j].slice(1)) + activeToolOffset.x;
|
||||
break;
|
||||
|
||||
case 'y':
|
||||
case "y":
|
||||
y = Number(args[j].slice(1)) + activeToolOffset.y;
|
||||
break;
|
||||
|
||||
case 'z':
|
||||
case "z":
|
||||
z = Number(args[j].slice(1));
|
||||
prevZ = z;
|
||||
break;
|
||||
|
||||
case 'e':
|
||||
case 'a':
|
||||
case 'b':
|
||||
case 'c':
|
||||
case "e":
|
||||
case "a":
|
||||
case "b":
|
||||
case "c":
|
||||
numSlice = Number(args[j].slice(1));
|
||||
if (relativeMode || relativeE) {
|
||||
prev_extrude[tool][argChar] = numSlice;
|
||||
@@ -489,11 +543,14 @@ var doParse = function () {
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined') {
|
||||
if (
|
||||
typeof x !== "undefined" ||
|
||||
typeof y !== "undefined" ||
|
||||
typeof z !== "undefined"
|
||||
) {
|
||||
addToModel = true;
|
||||
move = false;
|
||||
}
|
||||
|
||||
} else if (/^(?:G28)(\.\d+)?/i.test(line)) {
|
||||
args = line.split(/\s/);
|
||||
|
||||
@@ -504,14 +561,14 @@ var doParse = function () {
|
||||
z = 0;
|
||||
} else {
|
||||
for (j = 0; j < args.length; j++) {
|
||||
switch (argChar = args[j].charAt(0).toLowerCase()) {
|
||||
case 'x':
|
||||
switch ((argChar = args[j].charAt(0).toLowerCase())) {
|
||||
case "x":
|
||||
x = 0;
|
||||
break;
|
||||
case 'y':
|
||||
case "y":
|
||||
y = 0;
|
||||
break;
|
||||
case 'z':
|
||||
case "z":
|
||||
z = 0;
|
||||
break;
|
||||
default:
|
||||
@@ -521,17 +578,23 @@ var doParse = function () {
|
||||
}
|
||||
|
||||
// if it's the first layer and G28 was without z
|
||||
if (layer === 0 && typeof(z) === 'undefined') {
|
||||
if (layer === 0 && typeof z === "undefined") {
|
||||
z = 0;
|
||||
}
|
||||
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
|
||||
if (
|
||||
typeof x !== "undefined" ||
|
||||
typeof y !== "undefined" ||
|
||||
typeof z !== "undefined" ||
|
||||
retract !== 0
|
||||
) {
|
||||
addToModel = true;
|
||||
move = true;
|
||||
}
|
||||
} else if (/^(?:T\d+)/i.test(line)) {
|
||||
tool = Number(line.split(/\s/)[0].slice(1));
|
||||
if (!prev_extrude[tool]) prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0};
|
||||
if (!prev_extrude[tool])
|
||||
prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0};
|
||||
if (!prev_retract[tool]) prev_retract[tool] = 0;
|
||||
|
||||
activeToolOffset = toolOffsets[tool];
|
||||
@@ -540,7 +603,7 @@ var doParse = function () {
|
||||
|
||||
// If move is on a new height and it's not extruding and
|
||||
// it's not currently already in a Z-lift, assume it's possibly a Z-lift
|
||||
if (typeof(z) !== 'undefined' && z !== prevZ && !extrude && !zLift) {
|
||||
if (typeof z !== "undefined" && z !== prevZ && !extrude && !zLift) {
|
||||
zLift = true;
|
||||
zLiftZ = prevZ;
|
||||
}
|
||||
@@ -549,7 +612,7 @@ var doParse = function () {
|
||||
zLift = false;
|
||||
}
|
||||
|
||||
if (typeof(z) !== 'undefined' && z !== prevZ) {
|
||||
if (typeof z !== "undefined" && z !== prevZ) {
|
||||
if (z_heights[z] !== undefined) {
|
||||
layer = z_heights[z];
|
||||
} else {
|
||||
@@ -560,7 +623,7 @@ var doParse = function () {
|
||||
sendLayer = layer;
|
||||
sendLayerZ = z;
|
||||
prevZ = z;
|
||||
} else if (typeof(z) === 'undefined' && typeof(prevZ) !== 'undefined') {
|
||||
} else if (typeof z === "undefined" && typeof prevZ !== "undefined") {
|
||||
if (z_heights.hasOwnProperty(prevZ)) {
|
||||
layer = z_heights[prevZ];
|
||||
} else {
|
||||
@@ -581,7 +644,10 @@ var doParse = function () {
|
||||
extrude: extrude,
|
||||
retract: retract,
|
||||
noMove: !move,
|
||||
extrusion: (extrude || retract) && prev_extrude[tool]["abs"] ? prev_extrude[tool]["abs"] : 0,
|
||||
extrusion:
|
||||
(extrude || retract) && prev_extrude[tool]["abs"]
|
||||
? prev_extrude[tool]["abs"]
|
||||
: 0,
|
||||
prevX: prevX,
|
||||
prevY: prevY,
|
||||
prevZ: prevZ,
|
||||
@@ -601,7 +667,10 @@ var doParse = function () {
|
||||
// there's something to be checked in the Z-lift cache
|
||||
if (prevZ === zLiftZ) {
|
||||
zLiftMoves.forEach(function (zLiftMove) {
|
||||
model[zLiftMove.layer].splice(model[layer].indexOf(zLiftMove.command), 1);
|
||||
model[zLiftMove.layer].splice(
|
||||
model[layer].indexOf(zLiftMove.command),
|
||||
1
|
||||
);
|
||||
model[z_heights[zLiftZ]].push(zLiftMove.command);
|
||||
});
|
||||
}
|
||||
@@ -610,19 +679,22 @@ var doParse = function () {
|
||||
zLiftZ = undefined;
|
||||
}
|
||||
|
||||
|
||||
model[layer].push(command);
|
||||
}
|
||||
|
||||
if (move) {
|
||||
if (typeof(x) !== 'undefined') prevX = x;
|
||||
if (typeof(y) !== 'undefined') prevY = y;
|
||||
if (typeof x !== "undefined") prevX = x;
|
||||
if (typeof y !== "undefined") prevY = y;
|
||||
}
|
||||
|
||||
if (typeof(sendLayer) !== "undefined") {
|
||||
if (typeof sendLayer !== "undefined") {
|
||||
if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length !== 0) {
|
||||
lastSend = i;
|
||||
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100);
|
||||
sendMultiLayerToParent(
|
||||
sendMultiLayer,
|
||||
sendMultiLayerZ,
|
||||
(i / gcode.length) * 100
|
||||
);
|
||||
sendMultiLayer = [];
|
||||
sendMultiLayerZ = [];
|
||||
}
|
||||
@@ -632,10 +704,9 @@ var doParse = function () {
|
||||
sendLayerZ = undefined;
|
||||
}
|
||||
}
|
||||
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100);
|
||||
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, (i / gcode.length) * 100);
|
||||
};
|
||||
|
||||
|
||||
var parseGCode = function (message) {
|
||||
gcode = message.gcode;
|
||||
firstReport = message.options.firstReport;
|
||||
@@ -648,8 +719,8 @@ var parseGCode = function (message) {
|
||||
doParse();
|
||||
gcode = [];
|
||||
self.postMessage({
|
||||
"cmd": "returnModel",
|
||||
"msg": {}
|
||||
cmd: "returnModel",
|
||||
msg: {}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -664,7 +735,14 @@ var runAnalyze = function (message) {
|
||||
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};
|
||||
boundingBox = {
|
||||
minX: undefined,
|
||||
maxX: undefined,
|
||||
minY: undefined,
|
||||
maxY: undefined,
|
||||
minZ: undefined,
|
||||
maxZ: undefined
|
||||
};
|
||||
filamentByLayer = {};
|
||||
totalFilament = 0;
|
||||
printTime = 0;
|
||||
@@ -686,18 +764,17 @@ onmessage = function (e) {
|
||||
var data = e.data;
|
||||
// for some reason firefox doesn't garbage collect when something inside closures is deleted, so we delete and recreate whole object eaech time
|
||||
switch (data.cmd) {
|
||||
case 'parseGCode':
|
||||
case "parseGCode":
|
||||
parseGCode(data.msg);
|
||||
break;
|
||||
case 'setOption':
|
||||
case "setOption":
|
||||
setOption(data.msg);
|
||||
break;
|
||||
case 'analyzeModel':
|
||||
case "analyzeModel":
|
||||
runAnalyze(data.msg);
|
||||
break;
|
||||
|
||||
default:
|
||||
self.postMessage('Unknown command: ' + data.msg);
|
||||
self.postMessage("Unknown command: " + data.msg);
|
||||
}
|
||||
|
||||
};
|
||||
@@ -6,15 +6,16 @@
|
||||
|
||||
.bar {
|
||||
-webkit-transition: width 0s linear;
|
||||
-moz-transition: width 0s linear;
|
||||
-o-transition: width 0s linear;
|
||||
transition: width 0s linear;
|
||||
-moz-transition: width 0s linear;
|
||||
-o-transition: width 0s linear;
|
||||
transition: width 0s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.canvas_container {
|
||||
position: relative;
|
||||
&:hover, &:active {
|
||||
&:hover,
|
||||
&:active {
|
||||
outline: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,8 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
|
||||
var OctoPrintLoggingClient = function(base) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var OctoPrintLoggingClient = function (base) {
|
||||
this.base = base;
|
||||
|
||||
this.baseUrl = this.base.getBlueprintUrl("logging");
|
||||
@@ -14,47 +13,53 @@
|
||||
this.setupUrl = this.baseUrl + "setup";
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.get = function(opts) {
|
||||
OctoPrintLoggingClient.prototype.get = function (opts) {
|
||||
return this.base.get(this.baseUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.listLogs = function(opts) {
|
||||
OctoPrintLoggingClient.prototype.listLogs = function (opts) {
|
||||
return this.base.get(this.logsUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) {
|
||||
OctoPrintLoggingClient.prototype.deleteLog = function (file, opts) {
|
||||
var fileUrl = this.logsUrl + "/" + file;
|
||||
return this.base.delete(fileUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) {
|
||||
OctoPrintLoggingClient.prototype.downloadLog = function (file, opts) {
|
||||
var fileUrl = this.logsUrl + "/" + file;
|
||||
return this.base.download(fileUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) {
|
||||
OctoPrintLoggingClient.prototype.updateLevels = function (config, opts) {
|
||||
return this.base.putJson(this.setupUrl + "/levels", config, opts);
|
||||
};
|
||||
|
||||
//~~ wrapper for backwards compatibility
|
||||
|
||||
var DeprecatedOctoPrintLogsClient = function(base) {
|
||||
var DeprecatedOctoPrintLogsClient = function (base) {
|
||||
this.base = base;
|
||||
this.wrapped = this.base.plugins.logging;
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.list = function(opts) {
|
||||
log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead");
|
||||
DeprecatedOctoPrintLogsClient.prototype.list = function (opts) {
|
||||
log.warn(
|
||||
"OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead"
|
||||
);
|
||||
return this.wrapped.listLogs(opts);
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) {
|
||||
log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead");
|
||||
DeprecatedOctoPrintLogsClient.prototype.delete = function (file, opts) {
|
||||
log.warn(
|
||||
"OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead"
|
||||
);
|
||||
return this.wrapped.deleteLog(file, opts);
|
||||
};
|
||||
|
||||
DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) {
|
||||
log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead");
|
||||
DeprecatedOctoPrintLogsClient.prototype.download = function (file, opts) {
|
||||
log.warn(
|
||||
"OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead"
|
||||
);
|
||||
return this.wrapped.downloadLog(file, opts);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function LoggingViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -17,11 +17,11 @@ $(function() {
|
||||
|
||||
self.markedForDeletion = ko.observableArray([]);
|
||||
|
||||
self.availableLoggersSorted = ko.computed(function() {
|
||||
self.availableLoggersSorted = ko.computed(function () {
|
||||
return _.sortBy(self.availableLoggers());
|
||||
});
|
||||
|
||||
self.configuredLoggersSorted = ko.computed(function() {
|
||||
self.configuredLoggersSorted = ko.computed(function () {
|
||||
return _.sortBy(self.configuredLoggers(), function (o) {
|
||||
o.level();
|
||||
return o.component;
|
||||
@@ -32,54 +32,57 @@ $(function() {
|
||||
self.listHelper = new ItemListHelper(
|
||||
"logFiles",
|
||||
{
|
||||
"name": function(a, b) {
|
||||
name: function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase())
|
||||
return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase())
|
||||
return 1;
|
||||
return 0;
|
||||
},
|
||||
"modification": function(a, b) {
|
||||
modification: function (a, b) {
|
||||
// sorts descending
|
||||
if (a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
},
|
||||
"size": function(a, b) {
|
||||
size: function (a, b) {
|
||||
// sorts descending
|
||||
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)) {
|
||||
self.requestData = function () {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_LOGGING_MANAGE
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
OctoPrint.plugins.logging.get()
|
||||
.done(self.fromResponse);
|
||||
OctoPrint.plugins.logging.get().done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
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) {
|
||||
self.fromLogsResponse = function (response) {
|
||||
if (!response) return;
|
||||
|
||||
var files = response.files;
|
||||
if (files === undefined)
|
||||
return;
|
||||
if (files === undefined) return;
|
||||
|
||||
self.listHelper.updateItems(files);
|
||||
|
||||
@@ -87,15 +90,15 @@ $(function() {
|
||||
self.totalSpace(response.total);
|
||||
};
|
||||
|
||||
self.fromSetupResponse = function(response) {
|
||||
self.fromSetupResponse = function (response) {
|
||||
if (!response) return;
|
||||
|
||||
// levels
|
||||
var levels = [];
|
||||
var configuredLoggers = [];
|
||||
_.each(response.levels, function(level, logger) {
|
||||
_.each(response.levels, function (level, logger) {
|
||||
var item = {component: logger, level: ko.observable(level)};
|
||||
item.level.subscribe(function() {
|
||||
item.level.subscribe(function () {
|
||||
self.configuredLoggersHasChanged();
|
||||
});
|
||||
levels.push(item);
|
||||
@@ -108,69 +111,92 @@ $(function() {
|
||||
self.availableLoggers(availableLoggers);
|
||||
};
|
||||
|
||||
self.fromSerialLogResponse = function(response) {
|
||||
self.fromSerialLogResponse = function (response) {
|
||||
if (!response) return;
|
||||
|
||||
self.serialLogEnabled(response.enabled);
|
||||
};
|
||||
|
||||
self.fromPluginTimingsLogResponse = function(response) {
|
||||
self.fromPluginTimingsLogResponse = function (response) {
|
||||
if (!response) return;
|
||||
|
||||
self.pluginTimingsLogEnabled(response.enabled);
|
||||
};
|
||||
|
||||
self.serialLogPopoverContent = function() {
|
||||
self.serialLogPopoverContent = function () {
|
||||
return self.popoverContent("serial.log");
|
||||
};
|
||||
|
||||
self.pluginTimingsLogPopoverContent = function() {
|
||||
self.pluginTimingsLogPopoverContent = function () {
|
||||
return self.popoverContent("plugintimings.log");
|
||||
};
|
||||
|
||||
self.popoverContent = function(logfile) {
|
||||
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>";
|
||||
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>";
|
||||
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)) {
|
||||
self.addLogger = function () {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_LOGGING_MANAGE
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
var component = self.availableLoggersName();
|
||||
var level = self.availableLoggersLevel();
|
||||
|
||||
self.configuredLoggers.push({component: component, level: ko.observable(level)});
|
||||
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)) {
|
||||
self.removeLogger = function (logger) {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_LOGGING_MANAGE
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -180,64 +206,96 @@ $(function() {
|
||||
self.configuredLoggersHasChanged();
|
||||
};
|
||||
|
||||
self.removeFile = function(filename) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
|
||||
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);
|
||||
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);
|
||||
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.markFilesOnPage = function () {
|
||||
self.markedForDeletion(
|
||||
_.uniq(
|
||||
self
|
||||
.markedForDeletion()
|
||||
.concat(_.map(self.listHelper.paginatedItems(), "name"))
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
self.markAllFiles = function() {
|
||||
self.markAllFiles = function () {
|
||||
self.markedForDeletion(_.map(self.listHelper.allItems, "name"));
|
||||
};
|
||||
|
||||
self.clearMarkedFiles = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
|
||||
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)) {
|
||||
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();
|
||||
});
|
||||
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);
|
||||
showConfirmationDialog(
|
||||
_.sprintf(gettext("You are about to delete %(count)d log files."), {
|
||||
count: self.markedForDeletion().length
|
||||
}),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.onServerReconnect = self.onUserLoggedIn = self.onEventSettingsUpdated = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
|
||||
self.onServerReconnect = self.onUserLoggedIn = self.onEventSettingsUpdated = 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)) {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_LOGGING_MANAGE
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if ( self.configuredLoggersChanged ) {
|
||||
if (self.configuredLoggersChanged) {
|
||||
console.log("ConfiguredLoggers has changed. Saving!");
|
||||
var levels = {};
|
||||
_.each(self.configuredLoggers(), function(data) {
|
||||
_.each(self.configuredLoggers(), function (data) {
|
||||
levels[data.component] = data.level();
|
||||
});
|
||||
OctoPrint.plugins.logging.updateLevels(levels);
|
||||
@@ -246,20 +304,41 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._bulkRemove = function(files) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)) {
|
||||
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);
|
||||
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)});
|
||||
.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);
|
||||
});
|
||||
};
|
||||
@@ -277,15 +356,14 @@ $(function() {
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(files, function(filename) {
|
||||
_.each(files, function (filename) {
|
||||
var request = handler(filename);
|
||||
requests.push(request)
|
||||
requests.push(request);
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
@@ -295,6 +373,10 @@ $(function() {
|
||||
construct: LoggingViewModel,
|
||||
additionalNames: ["logsViewModel"],
|
||||
dependencies: ["loginStateViewModel", "accessViewModel"],
|
||||
elements: ["#settings_plugin_logging", "#navbar_plugin_logging_seriallog", "#navbar_plugin_logging_plugintimingslog"]
|
||||
elements: [
|
||||
"#settings_plugin_logging",
|
||||
"#navbar_plugin_logging_seriallog",
|
||||
"#navbar_plugin_logging_plugintimingslog"
|
||||
]
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
table {
|
||||
th, td {
|
||||
th,
|
||||
td {
|
||||
&.settings_logs_checkbox {
|
||||
text-align: center;
|
||||
width: 10px;
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintPiSupportClient = function(base) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var OctoPrintPiSupportClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPiSupportClient.prototype.get = function(opts) {
|
||||
OctoPrintPiSupportClient.prototype.get = function (opts) {
|
||||
return this.base.get(this.base.getSimpleApiUrl("pi_support"));
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
$(function() {
|
||||
|
||||
$(function () {
|
||||
function PiSupportViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -15,29 +14,39 @@ $(function() {
|
||||
self.currentIssue = ko.observable(false);
|
||||
self.pastIssue = ko.observable(false);
|
||||
|
||||
self.requestData = function() {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PI_SUPPORT_STATUS)) {
|
||||
self.requestData = function () {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_PI_SUPPORT_STATUS
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
OctoPrint.plugins.pi_support.get()
|
||||
.done(function(response) {
|
||||
// Raspberry Pi model
|
||||
self.model(response.model);
|
||||
OctoPrint.plugins.pi_support.get().done(function (response) {
|
||||
// Raspberry Pi model
|
||||
self.model(response.model);
|
||||
|
||||
// Throttle state
|
||||
self.fromThrottleState(response.throttle_state);
|
||||
// Throttle state
|
||||
self.fromThrottleState(response.throttle_state);
|
||||
|
||||
// OctoPi version
|
||||
$("#pi_support_footer").remove();
|
||||
if (!response.octopi_version) return;
|
||||
// OctoPi version
|
||||
$("#pi_support_footer").remove();
|
||||
if (!response.octopi_version) return;
|
||||
|
||||
var octoPiVersion = $("<li id='pi_support_footer'><small>" + gettext("OctoPi") + " " + "<span class='octopi_version'>" + response.octopi_version + "</span></small></li>");
|
||||
$("#footer_version").append(octoPiVersion);
|
||||
})
|
||||
var octoPiVersion = $(
|
||||
"<li id='pi_support_footer'><small>" +
|
||||
gettext("OctoPi") +
|
||||
" " +
|
||||
"<span class='octopi_version'>" +
|
||||
response.octopi_version +
|
||||
"</span></small></li>"
|
||||
);
|
||||
$("#footer_version").append(octoPiVersion);
|
||||
});
|
||||
};
|
||||
|
||||
self.fromThrottleState = function(state) {
|
||||
self.fromThrottleState = function (state) {
|
||||
self.currentUndervoltage(state.current_undervoltage);
|
||||
self.pastUndervoltage(state.past_undervoltage);
|
||||
self.currentOverheat(state.current_overheat);
|
||||
@@ -46,7 +55,7 @@ $(function() {
|
||||
self.pastIssue(state.past_issue);
|
||||
};
|
||||
|
||||
self.popoverContent = ko.pureComputed(function() {
|
||||
self.popoverContent = ko.pureComputed(function () {
|
||||
var undervoltageParagraphClasses = "muted";
|
||||
var undervoltageSymbolClasses = "";
|
||||
|
||||
@@ -69,24 +78,53 @@ $(function() {
|
||||
overheatParagraphClasses = "";
|
||||
}
|
||||
|
||||
return "<p class='" + undervoltageParagraphClasses + "'><strong class='" + undervoltageSymbolClasses + "'><i class=\"fa fa-bolt\"></i><i class=\"fa fa-exclamation\"></i></strong></strong> - " + gettext("Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi.") + "</p>"
|
||||
+ "<p class='" + overheatParagraphClasses + "'><strong class='" + overheatSymbolClasses + "'><i class=\"fa fa-thermometer-full\"></i><i class=\"fa fa-exclamation\"></i></strong> - " + gettext("Frequency capping due to overheating. Improve cooling of the CPU and GPU.") + "</p>"
|
||||
+ "<p>" + gettext("A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up.") + "</p>"
|
||||
+ "<p><small>" + gettext("Click the symbol in the navbar for more information.") + "</small></p>";
|
||||
return (
|
||||
"<p class='" +
|
||||
undervoltageParagraphClasses +
|
||||
"'><strong class='" +
|
||||
undervoltageSymbolClasses +
|
||||
'\'><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></strong></strong> - ' +
|
||||
gettext(
|
||||
"Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi."
|
||||
) +
|
||||
"</p>" +
|
||||
"<p class='" +
|
||||
overheatParagraphClasses +
|
||||
"'><strong class='" +
|
||||
overheatSymbolClasses +
|
||||
'\'><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></strong> - ' +
|
||||
gettext(
|
||||
"Frequency capping due to overheating. Improve cooling of the CPU and GPU."
|
||||
) +
|
||||
"</p>" +
|
||||
"<p>" +
|
||||
gettext(
|
||||
"A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up."
|
||||
) +
|
||||
"</p>" +
|
||||
"<p><small>" +
|
||||
gettext("Click the symbol in the navbar for more information.") +
|
||||
"</small></p>"
|
||||
);
|
||||
});
|
||||
|
||||
self.onStartup = self.onServerReconnect = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.onStartup = self.onServerReconnect = self.onUserLoggedIn = self.onUserLoggedOut = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onDataUpdaterPluginMessage = function(plugin, data) {
|
||||
self.onDataUpdaterPluginMessage = function (plugin, data) {
|
||||
if (plugin !== "pi_support") return;
|
||||
if (!data.hasOwnProperty("state") || !data.hasOwnProperty("type")) return;
|
||||
if (data.type !== "throttle_state") return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PI_SUPPORT_STATUS)) return;
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_PI_SUPPORT_STATUS
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
self.fromThrottleState(data.state);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintPluginManagerClient = function(base) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var OctoPrintPluginManagerClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
|
||||
OctoPrintPluginManagerClient.prototype.get = function (refresh, opts) {
|
||||
var refresh_repo, refresh_notices, refresh_orphans;
|
||||
if (_.isPlainObject(refresh)) {
|
||||
refresh_repo = refresh.repo || false;
|
||||
@@ -26,18 +26,26 @@
|
||||
if (refresh_notices) query.push("refresh_notices=true");
|
||||
if (refresh_orphans) query.push("refresh_orphans=true");
|
||||
|
||||
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
|
||||
return this.base.get(
|
||||
this.base.getSimpleApiUrl("pluginmanager") +
|
||||
(query.length ? "?" + query.join("&") : ""),
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) {
|
||||
OctoPrintPluginManagerClient.prototype.getWithRefresh = function (opts) {
|
||||
return this.get(true, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) {
|
||||
OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function (opts) {
|
||||
return this.get(false, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) {
|
||||
OctoPrintPluginManagerClient.prototype.install = function (
|
||||
pluginUrl,
|
||||
dependencyLinks,
|
||||
opts
|
||||
) {
|
||||
var data = {
|
||||
url: pluginUrl,
|
||||
dependency_links: !!dependencyLinks
|
||||
@@ -45,7 +53,12 @@
|
||||
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
|
||||
OctoPrintPluginManagerClient.prototype.reinstall = function (
|
||||
plugin,
|
||||
pluginUrl,
|
||||
dependencyLinks,
|
||||
opts
|
||||
) {
|
||||
var data = {
|
||||
url: pluginUrl,
|
||||
dependency_links: !!dependencyLinks,
|
||||
@@ -55,7 +68,7 @@
|
||||
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, cleanup, opts) {
|
||||
OctoPrintPluginManagerClient.prototype.uninstall = function (plugin, cleanup, opts) {
|
||||
// backwards compatibility to former argument list (plugin, opts)
|
||||
if (arguments.length === 2 && typeof cleanup === "object") {
|
||||
opts = cleanup;
|
||||
@@ -69,36 +82,42 @@
|
||||
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.cleanup = function(plugin, opts) {
|
||||
OctoPrintPluginManagerClient.prototype.cleanup = function (plugin, opts) {
|
||||
var data = {
|
||||
plugin: plugin
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "cleanup", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.cleanupAll = function(plugin, opts) {
|
||||
OctoPrintPluginManagerClient.prototype.cleanupAll = function (plugin, opts) {
|
||||
var data = {};
|
||||
return this.base.simpleApiCommand("pluginmanager", "cleanup_all", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
|
||||
OctoPrintPluginManagerClient.prototype.enable = function (plugin, opts) {
|
||||
var data = {
|
||||
plugin: plugin
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "enable", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) {
|
||||
OctoPrintPluginManagerClient.prototype.disable = function (plugin, opts) {
|
||||
var data = {
|
||||
plugin: plugin
|
||||
};
|
||||
return this.base.simpleApiCommand("pluginmanager", "disable", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.upload = function(file) {
|
||||
return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file);
|
||||
OctoPrintPluginManagerClient.prototype.upload = function (file) {
|
||||
return this.base.upload(
|
||||
this.base.getBlueprintUrl("pluginmanager") + "upload_archive",
|
||||
file
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient);
|
||||
OctoPrintClient.registerPluginComponent(
|
||||
"pluginmanager",
|
||||
OctoPrintPluginManagerClient
|
||||
);
|
||||
return OctoPrintPluginManagerClient;
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,8 +11,8 @@
|
||||
margin-bottom: 1em;
|
||||
|
||||
table {
|
||||
|
||||
th, td {
|
||||
th,
|
||||
td {
|
||||
&.settings_plugin_plugin_manager_plugins_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
@@ -50,8 +50,8 @@
|
||||
margin-bottom: 1em;
|
||||
|
||||
table {
|
||||
|
||||
th, td {
|
||||
th,
|
||||
td {
|
||||
&.settings_plugin_plugin_manager_orphans_id {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
var OctoPrintSoftwareUpdateClient = function(base) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var OctoPrintSoftwareUpdateClient = function (base) {
|
||||
this.base = base;
|
||||
|
||||
var url = this.base.getBlueprintUrl("softwareupdate");
|
||||
@@ -14,7 +14,11 @@
|
||||
this.configureUrl = url + "configure";
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) {
|
||||
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function (
|
||||
entries,
|
||||
force,
|
||||
opts
|
||||
) {
|
||||
if (arguments.length == 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
entries = params.entries;
|
||||
@@ -37,7 +41,7 @@
|
||||
return this.base.getWithQuery(this.checkUrl, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) {
|
||||
OctoPrintSoftwareUpdateClient.prototype.check = function (force, opts) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
force = params.force;
|
||||
@@ -47,7 +51,7 @@
|
||||
return this.checkEntries({entries: [], force: force, opts: opts});
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.update = function(targets, force, opts) {
|
||||
OctoPrintSoftwareUpdateClient.prototype.update = function (targets, force, opts) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
targets = params.targets;
|
||||
@@ -67,7 +71,7 @@
|
||||
return this.base.postJson(this.updateUrl, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) {
|
||||
OctoPrintSoftwareUpdateClient.prototype.updateAll = function (force, opts) {
|
||||
if (arguments.length === 1 && _.isObject(arguments[0])) {
|
||||
var params = arguments[0];
|
||||
force = params.force;
|
||||
@@ -80,10 +84,13 @@
|
||||
return this.base.postJson(this.updateUrl, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintSoftwareUpdateClient.prototype.configure = function(data, opts) {
|
||||
OctoPrintSoftwareUpdateClient.prototype.configure = function (data, opts) {
|
||||
return this.base.postJson(this.configureUrl, data, opts);
|
||||
}
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient);
|
||||
OctoPrintClient.registerPluginComponent(
|
||||
"softwareupdate",
|
||||
OctoPrintSoftwareUpdateClient
|
||||
);
|
||||
return OctoPrintSoftwareUpdateClient;
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function UsageViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -10,22 +10,26 @@ $(function() {
|
||||
self.active = ko.observable();
|
||||
self.required = false;
|
||||
|
||||
self.enableUsage = function() {
|
||||
self.enableUsage = function () {
|
||||
self.settingsViewModel.settings.plugins.tracking.enabled(true);
|
||||
self.decision(true);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.disableUsage = function() {
|
||||
self.disableUsage = function () {
|
||||
self.settingsViewModel.settings.plugins.tracking.enabled(false);
|
||||
self.decision(false);
|
||||
self._sendData();
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
self.onBeforeWizardTabChange = function (next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_tracking") || self.setup()) {
|
||||
if (
|
||||
!current ||
|
||||
!_.startsWith(current, "wizard_plugin_tracking") ||
|
||||
self.setup()
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -33,7 +37,7 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onBeforeWizardFinish = function() {
|
||||
self.onBeforeWizardFinish = function () {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (self.setup()) {
|
||||
@@ -44,18 +48,20 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.onWizardDetails = function (response) {
|
||||
self.required = response && response.tracking && response.tracking.required;
|
||||
};
|
||||
|
||||
self._showDecisionNeededDialog = function() {
|
||||
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.")
|
||||
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() {
|
||||
self._sendData = function () {
|
||||
var data = {
|
||||
plugins: {
|
||||
tracking: {
|
||||
@@ -65,23 +71,30 @@ $(function() {
|
||||
};
|
||||
|
||||
self.active(true);
|
||||
self.settingsViewModel.saveData(data)
|
||||
.done(function() {
|
||||
self.settingsViewModel
|
||||
.saveData(data)
|
||||
.done(function () {
|
||||
self.setup(true);
|
||||
self.active(false);
|
||||
})
|
||||
.fail(function() {
|
||||
.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'>" +
|
||||
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>.");
|
||||
"<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"}),
|
||||
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
|
||||
});
|
||||
|
||||
@@ -1 +1 @@
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
|
||||
@@ -3,14 +3,14 @@
|
||||
* web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
$(function () {
|
||||
var overlayElement = $("#login-overlay");
|
||||
var errorElement = $("#login-error");
|
||||
var offlineElement = $("#login-offline");
|
||||
var buttonElement = $("#login-button");
|
||||
var reconnectElement = $("#login-reconnect");
|
||||
|
||||
buttonElement.click(function() {
|
||||
buttonElement.click(function () {
|
||||
var usernameElement = $("#login-user");
|
||||
var passwordElement = $("#login-password");
|
||||
var rememberElement = $("#login-remember");
|
||||
@@ -22,11 +22,12 @@ $(function() {
|
||||
overlayElement.addClass("in");
|
||||
errorElement.removeClass("in");
|
||||
|
||||
OctoPrint.browser.login(username, password, remember)
|
||||
.done(function() {
|
||||
OctoPrint.browser
|
||||
.login(username, password, remember)
|
||||
.done(function () {
|
||||
location.reload();
|
||||
})
|
||||
.fail(function() {
|
||||
.fail(function () {
|
||||
usernameElement.val("");
|
||||
passwordElement.val("");
|
||||
|
||||
@@ -42,28 +43,28 @@ $(function() {
|
||||
OctoPrint.options.baseurl = BASE_URL;
|
||||
|
||||
var offlineTimer = undefined;
|
||||
var clearOfflineTimer = function() {
|
||||
var clearOfflineTimer = function () {
|
||||
if (offlineTimer !== undefined) {
|
||||
window.clearTimeout(offlineTimer);
|
||||
offlineTimer = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
OctoPrint.socket.onConnected = function() {
|
||||
OctoPrint.socket.onConnected = function () {
|
||||
clearOfflineTimer();
|
||||
buttonElement.prop("disabled", false);
|
||||
offlineElement.removeClass("in");
|
||||
};
|
||||
|
||||
OctoPrint.socket.onDisconnected = function() {
|
||||
OctoPrint.socket.onDisconnected = function () {
|
||||
clearOfflineTimer();
|
||||
offlineTimer = window.setTimeout(function() {
|
||||
offlineTimer = window.setTimeout(function () {
|
||||
buttonElement.prop("disabled", true);
|
||||
offlineElement.addClass("in");
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
reconnectElement.click(function() {
|
||||
reconnectElement.click(function () {
|
||||
OctoPrint.socket.reconnect();
|
||||
});
|
||||
|
||||
|
||||
@@ -13,15 +13,17 @@ body {
|
||||
-webkit-border-radius: 5px;
|
||||
-moz-border-radius: 5px;
|
||||
border-radius: 5px;
|
||||
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
box-shadow: 0 1px 2px rgba(0,0,0,.05);
|
||||
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
-moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
|
||||
.form-signin-heading, .checkbox {
|
||||
.form-signin-heading,
|
||||
.checkbox {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
input[type="text"], input[type="password"] {
|
||||
input[type="text"],
|
||||
input[type="password"] {
|
||||
font-size: 16px;
|
||||
height: auto;
|
||||
margin-bottom: 15px;
|
||||
@@ -58,8 +60,8 @@ body {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #000000;
|
||||
filter:alpha(opacity=50);
|
||||
-moz-opacity:0.5;
|
||||
filter: alpha(opacity=50);
|
||||
-moz-opacity: 0.5;
|
||||
-khtml-opacity: 0.5;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@
|
||||
opacity: 0.5;
|
||||
}
|
||||
50% {
|
||||
opacity: 1.0;
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
opacity: 0.5;
|
||||
@@ -102,9 +102,14 @@
|
||||
</style>
|
||||
<script>
|
||||
if (!String.prototype.endsWith) {
|
||||
String.prototype.endsWith = function(searchString, position) {
|
||||
String.prototype.endsWith = function (searchString, position) {
|
||||
var subjectString = this.toString();
|
||||
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
|
||||
if (
|
||||
typeof position !== "number" ||
|
||||
!isFinite(position) ||
|
||||
Math.floor(position) !== position ||
|
||||
position > subjectString.length
|
||||
) {
|
||||
position = subjectString.length;
|
||||
}
|
||||
position -= searchString.length;
|
||||
@@ -127,11 +132,11 @@
|
||||
|
||||
console.log("Pinging " + url);
|
||||
|
||||
img.onload = function() {
|
||||
img.onload = function () {
|
||||
callback("load");
|
||||
calledBack = true;
|
||||
};
|
||||
img.onerror = function() {
|
||||
img.onerror = function () {
|
||||
if (!calledBack) {
|
||||
callback("error");
|
||||
calledBack = true;
|
||||
@@ -139,7 +144,7 @@
|
||||
};
|
||||
|
||||
img.src = urlToUse;
|
||||
setTimeout(function() {
|
||||
setTimeout(function () {
|
||||
if (!calledBack) {
|
||||
callback("timeout");
|
||||
calledBack = true;
|
||||
@@ -147,7 +152,7 @@
|
||||
}, timeout);
|
||||
}
|
||||
|
||||
window.onload = function() {
|
||||
window.onload = function () {
|
||||
var intervals = [1, 1, 2, 3, 5, 8];
|
||||
var timeout = 1500;
|
||||
|
||||
@@ -180,7 +185,7 @@
|
||||
var reloadnow = window.document.getElementById("reloadnow");
|
||||
var reloadnowlink = window.document.getElementById("reloadnowlink");
|
||||
|
||||
var reload = function() {
|
||||
var reload = function () {
|
||||
var reloadUrl = baseUrl + currentQuery + currentFragment;
|
||||
if (reloadUrl == window.location.href) {
|
||||
window.location.reload(false);
|
||||
@@ -190,7 +195,7 @@
|
||||
};
|
||||
|
||||
var indexCached = false;
|
||||
var indexCachedCallback = function(result) {
|
||||
var indexCachedCallback = function (result) {
|
||||
if (indexCached) return;
|
||||
|
||||
if (result == "load") {
|
||||
@@ -207,20 +212,21 @@
|
||||
reload();
|
||||
} else {
|
||||
// cached.gif still not available, let's look at it again in a second
|
||||
cachedTimeout = setTimeout(function() {
|
||||
cachedTimeout = setTimeout(function () {
|
||||
ping(indexCachedUrl, timeout, indexCachedCallback);
|
||||
}, 1000)
|
||||
}, 1000);
|
||||
}
|
||||
};
|
||||
|
||||
var serverIsOnline = false;
|
||||
var serverOnlineCallback = function(result) {
|
||||
var serverOnlineCallback = function (result) {
|
||||
if (result == "load") {
|
||||
// our online.gif loaded, so the server is up, let's wait for it to become ready
|
||||
serverIsOnline = true;
|
||||
|
||||
message.innerText = "OctoPrint server started, waiting for it to get ready...";
|
||||
reloadnowlink.onclick = function() {
|
||||
message.innerText =
|
||||
"OctoPrint server started, waiting for it to get ready...";
|
||||
reloadnowlink.onclick = function () {
|
||||
indexCached = true; // not really, but we fake it
|
||||
|
||||
message.className = "pulsate1";
|
||||
@@ -238,20 +244,20 @@
|
||||
if (intervals.length) {
|
||||
interval = intervals.shift();
|
||||
}
|
||||
serverTimeout = setTimeout(function() {
|
||||
serverTimeout = setTimeout(function () {
|
||||
ping(serverOnlineUrl, timeout, serverOnlineCallback);
|
||||
}, interval * 1000)
|
||||
}, interval * 1000);
|
||||
}
|
||||
};
|
||||
|
||||
var backendOfflineCounter = 0;
|
||||
var backendOnlineCallback = function(result) {
|
||||
var backendOnlineCallback = function (result) {
|
||||
if (serverIsOnline) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (result == "load") {
|
||||
setTimeout(function() {
|
||||
setTimeout(function () {
|
||||
ping(backendOnlineUrl, timeout, backendOnlineCallback);
|
||||
}, 1000);
|
||||
return;
|
||||
@@ -267,9 +273,10 @@
|
||||
}
|
||||
|
||||
message.className = "red";
|
||||
message.innerHTML = "Looks like something went wrong during startup, the server is gone again. You should check <code>octoprint.log</code>.";
|
||||
message.innerHTML =
|
||||
"Looks like something went wrong during startup, the server is gone again. You should check <code>octoprint.log</code>.";
|
||||
} else {
|
||||
setTimeout(function() {
|
||||
setTimeout(function () {
|
||||
ping(backendOnlineUrl, timeout, backendOnlineCallback);
|
||||
}, 1000);
|
||||
}
|
||||
@@ -277,7 +284,7 @@
|
||||
|
||||
ping(backendOnlineUrl, timeout, backendOnlineCallback);
|
||||
ping(serverOnlineUrl, timeout, serverOnlineCallback);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
@@ -287,8 +294,17 @@
|
||||
<div class="outer">
|
||||
<div class="inner">
|
||||
<div class="content">
|
||||
<h1 id="message" class="pulsate3">OctoPrint is still starting up, please wait...</h1>
|
||||
<small id="reloadnow" style="display: none"><a id="reloadnowlink" class="normal" href="javascript:void(0)">Don't wait, reload now!</a></small>
|
||||
<h1 id="message" class="pulsate3">
|
||||
OctoPrint is still starting up, please wait...
|
||||
</h1>
|
||||
<small id="reloadnow" style="display: none"
|
||||
><a
|
||||
id="reloadnowlink"
|
||||
class="normal"
|
||||
href="javascript:void(0)"
|
||||
>Don't wait, reload now!</a
|
||||
></small
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
ko.bindingHandlers.allowBindings = {
|
||||
init: function (elem, valueAccessor) {
|
||||
return { controlsDescendantBindings: !valueAccessor() };
|
||||
return {controlsDescendantBindings: !valueAccessor()};
|
||||
}
|
||||
};
|
||||
ko.virtualElements.allowedBindings.allowBindings = true;
|
||||
@@ -1,10 +1,22 @@
|
||||
ko.bindingHandlers.contextMenu = {
|
||||
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
|
||||
init: function (
|
||||
element,
|
||||
valueAccessor,
|
||||
allBindingsAccessor,
|
||||
viewModel,
|
||||
bindingContext
|
||||
) {
|
||||
var val = ko.utils.unwrapObservable(valueAccessor());
|
||||
|
||||
$(element).contextMenu(val);
|
||||
},
|
||||
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
|
||||
update: function (
|
||||
element,
|
||||
valueAccessor,
|
||||
allBindingsAccessor,
|
||||
viewModel,
|
||||
bindingContext
|
||||
) {
|
||||
var val = ko.utils.unwrapObservable(valueAccessor());
|
||||
|
||||
$(element).contextMenu(val);
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
ko.bindingHandlers.copyWidth = {
|
||||
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
var node = ko.bindingHandlers.copyWidth._getReferenceNode(element, valueAccessor);
|
||||
ko.bindingHandlers.copyWidth._setWidth(node, element);
|
||||
ko.bindingHandlers.copyWidth._addResizeSensor(node, element);
|
||||
},
|
||||
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
var node = ko.bindingHandlers.copyWidth._getReferenceNode(element, valueAccessor);
|
||||
ko.bindingHandlers.copyWidth._setWidth(node, element);
|
||||
ko.bindingHandlers.copyWidth._addResizeSensor(node, element);
|
||||
},
|
||||
_setWidth: function(node, element) {
|
||||
_setWidth: function (node, element) {
|
||||
var width = node.width();
|
||||
if (!width) return;
|
||||
if ($(element).width() === width) return;
|
||||
element.style.width = width + "px";
|
||||
},
|
||||
_getReferenceNode: function(element, valueAccessor) {
|
||||
_getReferenceNode: function (element, valueAccessor) {
|
||||
var value = ko.utils.unwrapObservable(valueAccessor());
|
||||
if (!value) return;
|
||||
|
||||
@@ -36,12 +36,12 @@ ko.bindingHandlers.copyWidth = {
|
||||
}
|
||||
return node;
|
||||
},
|
||||
_addResizeSensor: function(node, element) {
|
||||
_addResizeSensor: function (node, element) {
|
||||
if (element.copyWidthSensor) {
|
||||
element.copyWidthSensor.detach();
|
||||
delete element.copyWidthSensor;
|
||||
}
|
||||
element.copyWidthSensor = new ResizeSensor(node, function() {
|
||||
element.copyWidthSensor = new ResizeSensor(node, function () {
|
||||
ko.bindingHandlers.copyWidth._setWidth(node, element);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
ko.bindingHandlers.invisible = {
|
||||
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
if (!valueAccessor()) return;
|
||||
ko.bindingHandlers.style.update(element, function() {
|
||||
return { visibility: 'hidden' };
|
||||
})
|
||||
ko.bindingHandlers.style.update(element, function () {
|
||||
return {visibility: "hidden"};
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,24 +1,36 @@
|
||||
ko.bindingHandlers.popover = {
|
||||
keys: ["title", "animation", "placement", "trigger", "delay", "content", "html"],
|
||||
|
||||
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
|
||||
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) {
|
||||
_.each(keys, function (key) {
|
||||
options[key] = ko.utils.unwrapObservable(val[key]);
|
||||
});
|
||||
|
||||
$(element).popover(options);
|
||||
},
|
||||
|
||||
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
|
||||
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) {
|
||||
_.each(keys, function (key) {
|
||||
value = ko.utils.unwrapObservable(val[key]);
|
||||
$(element).data("popover").options[key] = value;
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
ko.bindingHandlers.qrcode = {
|
||||
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
var val = ko.utils.unwrapObservable(valueAccessor());
|
||||
|
||||
var defaultOptions = {
|
||||
@@ -15,7 +15,7 @@ ko.bindingHandlers.qrcode = {
|
||||
};
|
||||
|
||||
var options = {};
|
||||
_.each(defaultOptions, function(value, key) {
|
||||
_.each(defaultOptions, function (value, key) {
|
||||
options[key] = ko.utils.unwrapObservable(val[key]) || value;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,38 +1,47 @@
|
||||
ko.bindingHandlers.slimScrolledForeach = {
|
||||
makeTemplateValueAccessor: function(valueAccessor) {
|
||||
makeTemplateValueAccessor: function (valueAccessor) {
|
||||
var modelValue = valueAccessor(),
|
||||
unwrappedValue = ko.utils.peekObservable(modelValue), // Unwrap without setting a dependency here
|
||||
result, slimscroll;
|
||||
unwrappedValue = ko.utils.peekObservable(modelValue), // Unwrap without setting a dependency here
|
||||
result,
|
||||
slimscroll;
|
||||
|
||||
// If unwrappedValue is the array, pass in the wrapped value on its own
|
||||
// The value will be unwrapped and tracked within the template binding
|
||||
// (See https://github.com/SteveSanderson/knockout/issues/523)
|
||||
if ((!unwrappedValue) || typeof unwrappedValue.length === "number") {
|
||||
result = { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
|
||||
if (!unwrappedValue || typeof unwrappedValue.length === "number") {
|
||||
result = {
|
||||
foreach: modelValue,
|
||||
templateEngine: ko.nativeTemplateEngine.instance
|
||||
};
|
||||
slimscroll = {};
|
||||
} else {
|
||||
// If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
|
||||
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
|
||||
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'];
|
||||
slimscroll = unwrappedValue["slimscroll"];
|
||||
}
|
||||
|
||||
return {accessor: function() { return result; }, slimscroll: slimscroll};
|
||||
return {
|
||||
accessor: function () {
|
||||
return result;
|
||||
},
|
||||
slimscroll: slimscroll
|
||||
};
|
||||
},
|
||||
|
||||
slimscroll: function(element, options) {
|
||||
slimscroll: function (element, options) {
|
||||
options = options || {};
|
||||
setTimeout(function() {
|
||||
setTimeout(function () {
|
||||
if (element.nodeName === "#comment") {
|
||||
// foreach is bound to a virtual element
|
||||
$(element.parentElement).slimScroll(options);
|
||||
@@ -42,16 +51,26 @@ ko.bindingHandlers.slimScrolledForeach = {
|
||||
}, 10);
|
||||
},
|
||||
|
||||
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
var prepped = ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(valueAccessor);
|
||||
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);
|
||||
return ko.bindingHandlers["template"]["init"](element, prepped.accessor);
|
||||
},
|
||||
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
var prepped = ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(valueAccessor);
|
||||
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);
|
||||
return ko.bindingHandlers["template"]["update"](
|
||||
element,
|
||||
prepped.accessor,
|
||||
allBindings,
|
||||
viewModel,
|
||||
bindingContext
|
||||
);
|
||||
}
|
||||
};
|
||||
ko.virtualElements.allowedBindings.slimScrolledForeach = true;
|
||||
@@ -6,10 +6,10 @@ ko.bindingHandlers.toggle = {
|
||||
var value = valueAccessor();
|
||||
|
||||
if (!ko.isObservable(value)) {
|
||||
throw new Error('toggle binding should be used only with observable values');
|
||||
throw new Error("toggle binding should be used only with observable values");
|
||||
}
|
||||
|
||||
$(element).on('click', function (event) {
|
||||
$(element).on("click", function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
var previousValue = ko.utils.unwrapObservable(value);
|
||||
@@ -18,6 +18,10 @@ ko.bindingHandlers.toggle = {
|
||||
},
|
||||
|
||||
update: function (element, valueAccessor) {
|
||||
ko.utils.toggleDomNodeCssClass(element, 'active', ko.utils.unwrapObservable(valueAccessor()));
|
||||
ko.utils.toggleDomNodeCssClass(
|
||||
element,
|
||||
"active",
|
||||
ko.utils.unwrapObservable(valueAccessor())
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -1,29 +1,34 @@
|
||||
ko.bindingHandlers.toggleContent = {
|
||||
init: function(element, valueAccessor) {
|
||||
init: function (element, valueAccessor) {
|
||||
var $elm = $(element),
|
||||
options = $.extend({
|
||||
class: null,
|
||||
container: null,
|
||||
parent: null,
|
||||
onComplete: function() {
|
||||
$(document).trigger("slideCompleted");
|
||||
}
|
||||
}, valueAccessor());
|
||||
options = $.extend(
|
||||
{
|
||||
class: null,
|
||||
container: null,
|
||||
parent: null,
|
||||
onComplete: function () {
|
||||
$(document).trigger("slideCompleted");
|
||||
}
|
||||
},
|
||||
valueAccessor()
|
||||
);
|
||||
|
||||
$elm.on("click", function(e) {
|
||||
$elm.on("click", function (e) {
|
||||
e.preventDefault();
|
||||
if(options.class) {
|
||||
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);
|
||||
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);
|
||||
$(options.container).stop().slideToggle("fast", options.onComplete);
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,11 +1,16 @@
|
||||
ko.bindingHandlers.valueWithInit = {
|
||||
init: function(element, valueAccessor, allBindingsAccessor, context) {
|
||||
init: function (element, valueAccessor, allBindingsAccessor, context) {
|
||||
var observable = valueAccessor();
|
||||
var value = element.value;
|
||||
|
||||
observable(value);
|
||||
|
||||
ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor, context);
|
||||
ko.bindingHandlers.value.init(
|
||||
element,
|
||||
valueAccessor,
|
||||
allBindingsAccessor,
|
||||
context
|
||||
);
|
||||
},
|
||||
update: ko.bindingHandlers.value.update
|
||||
};
|
||||
@@ -4,17 +4,17 @@
|
||||
} else {
|
||||
global.OctoPrintAccessClient = factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var baseAccessUrl = "api/access";
|
||||
|
||||
//~~ permissions client api
|
||||
|
||||
var OctoPrintAccessPermissionsClient = function(access) {
|
||||
var OctoPrintAccessPermissionsClient = function (access) {
|
||||
this.access = access;
|
||||
this.base = this.access.base;
|
||||
|
||||
var baseUrl = baseAccessUrl + "/permissions";
|
||||
this.url = function() {
|
||||
this.url = function () {
|
||||
if (arguments.length) {
|
||||
return baseUrl + "/" + Array.prototype.join.call(arguments, "/");
|
||||
} else {
|
||||
@@ -29,12 +29,12 @@
|
||||
|
||||
//~~ groups client api
|
||||
|
||||
var OctoPrintAccessGroupsClient = function(access) {
|
||||
var OctoPrintAccessGroupsClient = function (access) {
|
||||
this.access = access;
|
||||
this.base = this.access.base;
|
||||
|
||||
var baseUrl = baseAccessUrl + "/groups";
|
||||
this.url = function() {
|
||||
this.url = function () {
|
||||
if (arguments.length) {
|
||||
return baseUrl + "/" + Array.prototype.join.call(arguments, "/");
|
||||
} else {
|
||||
@@ -99,12 +99,12 @@
|
||||
|
||||
//~~ users client api
|
||||
|
||||
var OctoPrintAccessUsersClient = function(access) {
|
||||
var OctoPrintAccessUsersClient = function (access) {
|
||||
this.access = access;
|
||||
this.base = this.access.base;
|
||||
|
||||
var baseUrl = baseAccessUrl + "/users";
|
||||
this.url = function() {
|
||||
this.url = function () {
|
||||
if (arguments.length) {
|
||||
return baseUrl + "/" + Array.prototype.join.call(arguments, "/");
|
||||
} else {
|
||||
@@ -119,7 +119,9 @@
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.add = function (user, opts) {
|
||||
if (!user.name || !user.password) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("Both user's name and password need to be set");
|
||||
throw new OctoPrintClient.InvalidArgumentError(
|
||||
"Both user's name and password need to be set"
|
||||
);
|
||||
}
|
||||
|
||||
var data = {
|
||||
@@ -142,7 +144,14 @@
|
||||
return this.base.get(this.url(name), opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.update = function (name, active, admin, permissions, groups, opts) {
|
||||
OctoPrintAccessUsersClient.prototype.update = function (
|
||||
name,
|
||||
active,
|
||||
admin,
|
||||
permissions,
|
||||
groups,
|
||||
opts
|
||||
) {
|
||||
if (!name) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
@@ -164,9 +173,15 @@
|
||||
return this.base.delete(this.url(name), opts);
|
||||
};
|
||||
|
||||
OctoPrintAccessUsersClient.prototype.changePassword = function (name, password, opts) {
|
||||
OctoPrintAccessUsersClient.prototype.changePassword = function (
|
||||
name,
|
||||
password,
|
||||
opts
|
||||
) {
|
||||
if (!name || !password) {
|
||||
throw new OctoPrintClient.InvalidArgumentError("user name and password must be set");
|
||||
throw new OctoPrintClient.InvalidArgumentError(
|
||||
"user name and password must be set"
|
||||
);
|
||||
}
|
||||
|
||||
var data = {
|
||||
@@ -208,7 +223,7 @@
|
||||
return this.base.patchJson(this.url(name, "settings"), settings, opts);
|
||||
};
|
||||
|
||||
var OctoPrintAccessClient = function(base) {
|
||||
var OctoPrintAccessClient = function (base) {
|
||||
this.base = base;
|
||||
|
||||
this.permissions = new OctoPrintAccessPermissionsClient(this);
|
||||
|
||||
@@ -5,26 +5,26 @@
|
||||
global.OctoPrintClient = factory(global.$, global._);
|
||||
global.OctoPrint = new global.OctoPrintClient();
|
||||
}
|
||||
})(this, function($, _) {
|
||||
var PluginRegistry = function(base) {
|
||||
})(this, function ($, _) {
|
||||
var PluginRegistry = function (base) {
|
||||
this.base = base;
|
||||
this.components = {};
|
||||
};
|
||||
|
||||
var OctoPrintClient = function(options) {
|
||||
var OctoPrintClient = function (options) {
|
||||
this.options = options || {
|
||||
"baseurl": undefined,
|
||||
"apikey": undefined,
|
||||
"locale": undefined
|
||||
baseurl: undefined,
|
||||
apikey: undefined,
|
||||
locale: undefined
|
||||
};
|
||||
|
||||
this.components = {};
|
||||
this.plugins = new PluginRegistry(this);
|
||||
};
|
||||
|
||||
OctoPrintClient.registerComponent = function(name, component) {
|
||||
OctoPrintClient.registerComponent = function (name, component) {
|
||||
Object.defineProperty(OctoPrintClient.prototype, name, {
|
||||
get: function() {
|
||||
get: function () {
|
||||
if (this.components[name] !== undefined) {
|
||||
return this.components[name];
|
||||
}
|
||||
@@ -32,15 +32,15 @@
|
||||
var instance = new component(this);
|
||||
this.components[name] = instance;
|
||||
return instance;
|
||||
},
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: false
|
||||
});
|
||||
};
|
||||
|
||||
OctoPrintClient.registerPluginComponent = function(name, component) {
|
||||
OctoPrintClient.registerPluginComponent = function (name, component) {
|
||||
Object.defineProperty(PluginRegistry.prototype, name, {
|
||||
get: function() {
|
||||
get: function () {
|
||||
if (this.components[name] !== undefined) {
|
||||
return this.components[name];
|
||||
}
|
||||
@@ -54,7 +54,7 @@
|
||||
});
|
||||
};
|
||||
|
||||
var noCache = function(opts) {
|
||||
var noCache = function (opts) {
|
||||
opts = opts || {};
|
||||
|
||||
var params = $.extend({}, opts);
|
||||
@@ -64,7 +64,7 @@
|
||||
return params;
|
||||
};
|
||||
|
||||
var contentTypeJson = function(opts) {
|
||||
var contentTypeJson = function (opts) {
|
||||
opts = opts || {};
|
||||
|
||||
var params = $.extend({}, opts);
|
||||
@@ -73,7 +73,7 @@
|
||||
return params;
|
||||
};
|
||||
|
||||
var contentTypeFalse = function(opts) {
|
||||
var contentTypeFalse = function (opts) {
|
||||
opts = opts || {};
|
||||
|
||||
var params = $.extend({}, opts);
|
||||
@@ -82,7 +82,7 @@
|
||||
return params;
|
||||
};
|
||||
|
||||
var noProcessData = function(opts) {
|
||||
var noProcessData = function (opts) {
|
||||
opts = opts || {};
|
||||
|
||||
var params = $.extend({}, opts);
|
||||
@@ -91,7 +91,7 @@
|
||||
return params;
|
||||
};
|
||||
|
||||
var replaceUndefinedWithNull = function(key, value) {
|
||||
var replaceUndefinedWithNull = function (key, value) {
|
||||
if (value === undefined) {
|
||||
return null;
|
||||
} else {
|
||||
@@ -99,7 +99,7 @@
|
||||
}
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.getBaseUrl = function() {
|
||||
OctoPrintClient.prototype.getBaseUrl = function () {
|
||||
var url = this.options.baseurl;
|
||||
if (!_.endsWith(url, "/")) {
|
||||
url = url + "/";
|
||||
@@ -107,7 +107,7 @@
|
||||
return url;
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.getRequestHeaders = function(additional) {
|
||||
OctoPrintClient.prototype.getRequestHeaders = function (additional) {
|
||||
additional = additional || {};
|
||||
|
||||
var headers = $.extend({}, additional);
|
||||
@@ -122,7 +122,7 @@
|
||||
return headers;
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.ajax = function(method, url, opts) {
|
||||
OctoPrintClient.prototype.ajax = function (method, url, opts) {
|
||||
opts = opts || {};
|
||||
|
||||
method = opts.method || method || "GET";
|
||||
@@ -144,7 +144,7 @@
|
||||
return $.ajax(urlToCall, params);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.ajaxWithData = function(method, url, data, opts) {
|
||||
OctoPrintClient.prototype.ajaxWithData = function (method, url, data, opts) {
|
||||
opts = opts || {};
|
||||
|
||||
var params = $.extend({}, opts);
|
||||
@@ -153,58 +153,70 @@
|
||||
return this.ajax(method, url, params);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.get = function(url, opts) {
|
||||
OctoPrintClient.prototype.get = function (url, opts) {
|
||||
return this.ajax("GET", url, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.getWithQuery = function(url, data, opts) {
|
||||
OctoPrintClient.prototype.getWithQuery = function (url, data, opts) {
|
||||
return this.ajaxWithData("GET", url, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.post = function(url, data, opts) {
|
||||
OctoPrintClient.prototype.post = function (url, data, opts) {
|
||||
return this.ajaxWithData("POST", url, data, noCache(opts));
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.postForm = function(url, data, opts) {
|
||||
OctoPrintClient.prototype.postForm = function (url, data, opts) {
|
||||
var form = new FormData();
|
||||
_.each(data, function(value, key) {
|
||||
_.each(data, function (value, key) {
|
||||
form.append(key, value);
|
||||
});
|
||||
|
||||
return this.post(url, form, contentTypeFalse(noProcessData(opts)));
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.postJson = function(url, data, opts) {
|
||||
return this.post(url, JSON.stringify(data, replaceUndefinedWithNull), contentTypeJson(opts));
|
||||
OctoPrintClient.prototype.postJson = function (url, data, opts) {
|
||||
return this.post(
|
||||
url,
|
||||
JSON.stringify(data, replaceUndefinedWithNull),
|
||||
contentTypeJson(opts)
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.put = function(url, data, opts) {
|
||||
OctoPrintClient.prototype.put = function (url, data, opts) {
|
||||
return this.ajaxWithData("PUT", url, data, noCache(opts));
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.putJson = function(url, data, opts) {
|
||||
return this.put(url, JSON.stringify(data, replaceUndefinedWithNull), contentTypeJson(opts));
|
||||
OctoPrintClient.prototype.putJson = function (url, data, opts) {
|
||||
return this.put(
|
||||
url,
|
||||
JSON.stringify(data, replaceUndefinedWithNull),
|
||||
contentTypeJson(opts)
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.patch = function(url, data, opts) {
|
||||
OctoPrintClient.prototype.patch = function (url, data, opts) {
|
||||
return this.ajaxWithData("PATCH", url, data, noCache(opts));
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.patchJson = function(url, data, opts) {
|
||||
return this.patch(url, JSON.stringify(data, replaceUndefinedWithNull), contentTypeJson(opts));
|
||||
OctoPrintClient.prototype.patchJson = function (url, data, opts) {
|
||||
return this.patch(
|
||||
url,
|
||||
JSON.stringify(data, replaceUndefinedWithNull),
|
||||
contentTypeJson(opts)
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.delete = function(url, opts) {
|
||||
OctoPrintClient.prototype.delete = function (url, opts) {
|
||||
return this.ajax("DELETE", url, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.download = function(url, opts) {
|
||||
OctoPrintClient.prototype.download = function (url, opts) {
|
||||
var params = $.extend({}, opts || {});
|
||||
params.dataType = "text";
|
||||
return this.get(url, params);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.upload = function(url, file, filename, additional) {
|
||||
OctoPrintClient.prototype.upload = function (url, file, filename, additional) {
|
||||
additional = additional || {};
|
||||
|
||||
var fileData;
|
||||
@@ -222,19 +234,20 @@
|
||||
var form = new FormData();
|
||||
form.append("file", fileData, filename);
|
||||
|
||||
_.each(additional, function(value, key) {
|
||||
_.each(additional, function (value, key) {
|
||||
form.append(key, value);
|
||||
});
|
||||
|
||||
var deferred = $.Deferred();
|
||||
|
||||
var request = new XMLHttpRequest();
|
||||
request.onreadystatechange = function() {
|
||||
request.onreadystatechange = function () {
|
||||
if (request.readyState == 4) {
|
||||
deferred.notify({loaded: filesize, total: filesize});
|
||||
|
||||
var success = request.status >= 200 && request.status < 300
|
||||
|| request.status === 304;
|
||||
var success =
|
||||
(request.status >= 200 && request.status < 300) ||
|
||||
request.status === 304;
|
||||
var error, json, statusText;
|
||||
|
||||
try {
|
||||
@@ -256,16 +269,16 @@
|
||||
}
|
||||
}
|
||||
};
|
||||
request.ontimeout = function() {
|
||||
request.ontimeout = function () {
|
||||
deferred.reject([request, "timeout", "Timeout"]);
|
||||
};
|
||||
request.upload.addEventListener("loadstart", function(e) {
|
||||
request.upload.addEventListener("loadstart", function (e) {
|
||||
deferred.notify({loaded: e.loaded, total: e.total});
|
||||
});
|
||||
request.upload.addEventListener("progress", function(e) {
|
||||
request.upload.addEventListener("progress", function (e) {
|
||||
deferred.notify({loaded: e.loaded, total: e.total});
|
||||
});
|
||||
request.upload.addEventListener("loadend", function(e) {
|
||||
request.upload.addEventListener("loadend", function (e) {
|
||||
deferred.notify({loaded: e.loaded, total: e.total});
|
||||
});
|
||||
|
||||
@@ -277,7 +290,7 @@
|
||||
}
|
||||
|
||||
request.open("POST", urlToCall);
|
||||
_.each(headers, function(value, key) {
|
||||
_.each(headers, function (value, key) {
|
||||
request.setRequestHeader(key, value);
|
||||
});
|
||||
request.send(form);
|
||||
@@ -285,7 +298,7 @@
|
||||
return deferred.promise();
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.issueCommand = function(url, command, payload, opts) {
|
||||
OctoPrintClient.prototype.issueCommand = function (url, command, payload, opts) {
|
||||
payload = payload || {};
|
||||
|
||||
var data = $.extend({}, payload);
|
||||
@@ -294,38 +307,48 @@
|
||||
return this.postJson(url, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.getSimpleApiUrl = function(plugin) {
|
||||
OctoPrintClient.prototype.getSimpleApiUrl = function (plugin) {
|
||||
return "api/plugin/" + plugin;
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.simpleApiGet = function(plugin, opts) {
|
||||
OctoPrintClient.prototype.simpleApiGet = function (plugin, opts) {
|
||||
return this.get(OctoPrintClient.prototype.getSimpleApiUrl(plugin), opts);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.simpleApiCommand = function(plugin, command, payload, opts) {
|
||||
return this.issueCommand(OctoPrintClient.prototype.getSimpleApiUrl(plugin), command, payload, opts);
|
||||
OctoPrintClient.prototype.simpleApiCommand = function (
|
||||
plugin,
|
||||
command,
|
||||
payload,
|
||||
opts
|
||||
) {
|
||||
return this.issueCommand(
|
||||
OctoPrintClient.prototype.getSimpleApiUrl(plugin),
|
||||
command,
|
||||
payload,
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.getBlueprintUrl = function(plugin) {
|
||||
OctoPrintClient.prototype.getBlueprintUrl = function (plugin) {
|
||||
return "plugin/" + plugin + "/";
|
||||
};
|
||||
|
||||
OctoPrintClient.createRejectedDeferred = function() {
|
||||
OctoPrintClient.createRejectedDeferred = function () {
|
||||
var deferred = $.Deferred();
|
||||
deferred.reject(arguments);
|
||||
return deferred;
|
||||
};
|
||||
|
||||
OctoPrintClient.createCustomException = function(name) {
|
||||
OctoPrintClient.createCustomException = function (name) {
|
||||
var constructor;
|
||||
|
||||
if (_.isFunction(name)) {
|
||||
constructor = name;
|
||||
} else {
|
||||
constructor = function(message) {
|
||||
constructor = function (message) {
|
||||
this.name = name;
|
||||
this.message = message;
|
||||
this.stack = (new Error()).stack;
|
||||
this.stack = new Error().stack;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -335,23 +358,61 @@
|
||||
return constructor;
|
||||
};
|
||||
|
||||
OctoPrintClient.InvalidArgumentError = OctoPrintClient.createCustomException("InvalidArgumentError");
|
||||
OctoPrintClient.InvalidArgumentError = OctoPrintClient.createCustomException(
|
||||
"InvalidArgumentError"
|
||||
);
|
||||
|
||||
OctoPrintClient.deprecated = function (deprecatedFct, newFct, fn) {
|
||||
return function() {
|
||||
console.warn(deprecatedFct + " is deprecated, please use the new " + newFct + " function instead");
|
||||
return function () {
|
||||
console.warn(
|
||||
deprecatedFct +
|
||||
" is deprecated, please use the new " +
|
||||
newFct +
|
||||
" function instead"
|
||||
);
|
||||
return fn.apply(this, arguments);
|
||||
};
|
||||
};
|
||||
|
||||
OctoPrintClient.deprecatedMethod = function(object, oldNamespace, oldFct, newNamespace, newFct, fn) {
|
||||
object[oldFct] = OctoPrintClient.deprecated(oldNamespace + "." + oldFct, newNamespace + "." + newFct, fn);
|
||||
OctoPrintClient.deprecatedMethod = function (
|
||||
object,
|
||||
oldNamespace,
|
||||
oldFct,
|
||||
newNamespace,
|
||||
newFct,
|
||||
fn
|
||||
) {
|
||||
object[oldFct] = OctoPrintClient.deprecated(
|
||||
oldNamespace + "." + oldFct,
|
||||
newNamespace + "." + newFct,
|
||||
fn
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintClient.deprecatedVariable = function(object, oldNamespace, oldVar, newNamespace, newVar, getter, setter) {
|
||||
OctoPrintClient.deprecatedVariable = function (
|
||||
object,
|
||||
oldNamespace,
|
||||
oldVar,
|
||||
newNamespace,
|
||||
newVar,
|
||||
getter,
|
||||
setter
|
||||
) {
|
||||
Object.defineProperty(object, oldVar, {
|
||||
get: function() { return OctoPrintClient.deprecated(oldNamespace + "." + oldVar, newNamespace + "." + newVar, getter)(); },
|
||||
set: function(val) { OctoPrintClient.deprecated(oldNamespace + "." + oldVar, newNamespace + "." + newVar, setter)(val); }
|
||||
get: function () {
|
||||
return OctoPrintClient.deprecated(
|
||||
oldNamespace + "." + oldVar,
|
||||
newNamespace + "." + newVar,
|
||||
getter
|
||||
)();
|
||||
},
|
||||
set: function (val) {
|
||||
OctoPrintClient.deprecated(
|
||||
oldNamespace + "." + oldVar,
|
||||
newNamespace + "." + newVar,
|
||||
setter
|
||||
)(val);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -4,15 +4,20 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var loginUrl = "api/login";
|
||||
var logoutUrl = "api/logout";
|
||||
|
||||
var OctoPrintBrowserClient = function(base) {
|
||||
var OctoPrintBrowserClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintBrowserClient.prototype.login = function(username, password, remember, opts) {
|
||||
OctoPrintBrowserClient.prototype.login = function (
|
||||
username,
|
||||
password,
|
||||
remember,
|
||||
opts
|
||||
) {
|
||||
var data = {
|
||||
user: username,
|
||||
pass: password,
|
||||
@@ -21,11 +26,11 @@
|
||||
return this.base.postJson(loginUrl, data, opts);
|
||||
};
|
||||
|
||||
OctoPrintBrowserClient.prototype.passiveLogin = function(opts) {
|
||||
OctoPrintBrowserClient.prototype.passiveLogin = function (opts) {
|
||||
return this.base.postJson(loginUrl, {passive: true}, opts);
|
||||
};
|
||||
|
||||
OctoPrintBrowserClient.prototype.logout = function(opts) {
|
||||
OctoPrintBrowserClient.prototype.logout = function (opts) {
|
||||
return this.base.postJson(logoutUrl, {}, opts);
|
||||
};
|
||||
|
||||
|
||||
@@ -4,26 +4,26 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var url = "api/connection";
|
||||
|
||||
var OctoPrintConnectionClient = function(base) {
|
||||
var OctoPrintConnectionClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintConnectionClient.prototype.getSettings = function(opts) {
|
||||
OctoPrintConnectionClient.prototype.getSettings = function (opts) {
|
||||
return this.base.get(url, opts);
|
||||
};
|
||||
|
||||
OctoPrintConnectionClient.prototype.connect = function(data, opts) {
|
||||
OctoPrintConnectionClient.prototype.connect = function (data, opts) {
|
||||
return this.base.issueCommand(url, "connect", data || {}, opts);
|
||||
};
|
||||
|
||||
OctoPrintConnectionClient.prototype.disconnect = function(opts) {
|
||||
OctoPrintConnectionClient.prototype.disconnect = function (opts) {
|
||||
return this.base.issueCommand(url, "disconnect", {}, opts);
|
||||
};
|
||||
|
||||
OctoPrintConnectionClient.prototype.fakeAck = function(opts) {
|
||||
OctoPrintConnectionClient.prototype.fakeAck = function (opts) {
|
||||
return this.base.issueCommand(url, "fake_ack", {}, opts);
|
||||
};
|
||||
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var customUrl = "api/printer/command/custom";
|
||||
var commandUrl = "api/printer/command";
|
||||
|
||||
var OctoPrintControlClient = function(base) {
|
||||
var OctoPrintControlClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
@@ -16,7 +16,11 @@
|
||||
return this.base.get(customUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintControlClient.prototype.sendGcodeWithParameters = function(commands, parameters, opts) {
|
||||
OctoPrintControlClient.prototype.sendGcodeWithParameters = function (
|
||||
commands,
|
||||
parameters,
|
||||
opts
|
||||
) {
|
||||
commands = commands || [];
|
||||
parameters = parameters || {};
|
||||
|
||||
@@ -24,22 +28,35 @@
|
||||
commands = [commands];
|
||||
}
|
||||
|
||||
return this.base.postJson(commandUrl, {
|
||||
commands: commands,
|
||||
parameters: parameters
|
||||
}, opts);
|
||||
return this.base.postJson(
|
||||
commandUrl,
|
||||
{
|
||||
commands: commands,
|
||||
parameters: parameters
|
||||
},
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintControlClient.prototype.sendGcodeScriptWithParameters = function(script, context, parameters, opts) {
|
||||
OctoPrintControlClient.prototype.sendGcodeScriptWithParameters = function (
|
||||
script,
|
||||
context,
|
||||
parameters,
|
||||
opts
|
||||
) {
|
||||
script = script || "";
|
||||
context = context || {};
|
||||
parameters = parameters || {};
|
||||
|
||||
return this.base.postJson(commandUrl, {
|
||||
script: script,
|
||||
context: context,
|
||||
parameters: parameters
|
||||
}, opts);
|
||||
return this.base.postJson(
|
||||
commandUrl,
|
||||
{
|
||||
script: script,
|
||||
context: context,
|
||||
parameters: parameters
|
||||
},
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintControlClient.prototype.sendGcode = function (commands, opts) {
|
||||
|
||||
@@ -1,42 +1,43 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === 'function' && define.amd) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrintClient", "jquery", "lodash"], factory);
|
||||
} else {
|
||||
factory(global.OctoPrintClient, global.$, global._);
|
||||
}
|
||||
})(this, function(OctoPrintClient, $, _) {
|
||||
})(this, function (OctoPrintClient, $, _) {
|
||||
var url = "api/files";
|
||||
var downloadUrl = "downloads/files";
|
||||
|
||||
var OctoPrintFilesClient = function(base) {
|
||||
var OctoPrintFilesClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
var resourceForLocation = function(location) {
|
||||
var resourceForLocation = function (location) {
|
||||
return url + "/" + location;
|
||||
};
|
||||
|
||||
var downloadForLocation = function(location) {
|
||||
var downloadForLocation = function (location) {
|
||||
return downloadUrl + "/" + location;
|
||||
};
|
||||
|
||||
var downloadForEntry = function(location, filename) {
|
||||
var downloadForEntry = function (location, filename) {
|
||||
return downloadForLocation(location) + "/" + filename;
|
||||
};
|
||||
|
||||
var resourceForEntry = function(location, filename) {
|
||||
var resourceForEntry = function (location, filename) {
|
||||
return resourceForLocation(location) + "/" + filename;
|
||||
};
|
||||
|
||||
var preProcessList = function(response) {
|
||||
var recursiveCheck = function(element, index, list) {
|
||||
if (!element.hasOwnProperty("parent")) element.parent = { children: list, parent: undefined };
|
||||
var preProcessList = function (response) {
|
||||
var recursiveCheck = function (element, index, list) {
|
||||
if (!element.hasOwnProperty("parent"))
|
||||
element.parent = {children: list, parent: undefined};
|
||||
if (!element.hasOwnProperty("size")) element.size = undefined;
|
||||
if (!element.hasOwnProperty("date")) element.date = undefined;
|
||||
|
||||
if (element.type == "folder") {
|
||||
element.weight = 0;
|
||||
_.each(element.children, function(e, i, l) {
|
||||
_.each(element.children, function (e, i, l) {
|
||||
e.parent = element;
|
||||
recursiveCheck(e, i, l);
|
||||
element.weight += e.weight;
|
||||
@@ -48,7 +49,7 @@
|
||||
_.each(response.files, recursiveCheck);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.get = function(location, entryname, opts) {
|
||||
OctoPrintFilesClient.prototype.get = function (location, entryname, opts) {
|
||||
return this.base.get(resourceForEntry(location, entryname), opts);
|
||||
};
|
||||
|
||||
@@ -64,17 +65,27 @@
|
||||
query.force = force;
|
||||
}
|
||||
|
||||
return this.base.getWithQuery(url, query, opts)
|
||||
.done(preProcessList);
|
||||
return this.base.getWithQuery(url, query, opts).done(preProcessList);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.listForLocation = function (location, recursively, opts) {
|
||||
OctoPrintFilesClient.prototype.listForLocation = function (
|
||||
location,
|
||||
recursively,
|
||||
opts
|
||||
) {
|
||||
recursively = recursively || false;
|
||||
return this.base.getWithQuery(resourceForLocation(location), {recursive: recursively}, opts)
|
||||
return this.base
|
||||
.getWithQuery(resourceForLocation(location), {recursive: recursively}, opts)
|
||||
.done(preProcessList);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.issueEntryCommand = function(location, entryname, command, data, opts) {
|
||||
OctoPrintFilesClient.prototype.issueEntryCommand = function (
|
||||
location,
|
||||
entryname,
|
||||
command,
|
||||
data,
|
||||
opts
|
||||
) {
|
||||
var url = resourceForEntry(location, entryname);
|
||||
return this.base.issueCommand(url, command, data, opts);
|
||||
};
|
||||
@@ -94,20 +105,31 @@
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.slice = function (location, path, parameters, opts) {
|
||||
return this.issueEntryCommand(location, path, "slice",
|
||||
parameters || {}, opts);
|
||||
return this.issueEntryCommand(location, path, "slice", parameters || {}, opts);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.delete = function (location, path, opts) {
|
||||
return this.base.delete(resourceForEntry(location, path), opts);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.copy = function(location, path, destination, opts) {
|
||||
return this.issueEntryCommand(location, path, "copy", { destination: destination }, opts);
|
||||
OctoPrintFilesClient.prototype.copy = function (location, path, destination, opts) {
|
||||
return this.issueEntryCommand(
|
||||
location,
|
||||
path,
|
||||
"copy",
|
||||
{destination: destination},
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.move = function(location, path, destination, opts) {
|
||||
return this.issueEntryCommand(location, path, "move", { destination: destination }, opts);
|
||||
OctoPrintFilesClient.prototype.move = function (location, path, destination, opts) {
|
||||
return this.issueEntryCommand(
|
||||
location,
|
||||
path,
|
||||
"move",
|
||||
{destination: destination},
|
||||
opts
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.createFolder = function (location, name, path, opts) {
|
||||
@@ -129,32 +151,32 @@
|
||||
return this.base.upload(resourceForLocation(location), file, filename, data);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.download = function(location, path, opts) {
|
||||
OctoPrintFilesClient.prototype.download = function (location, path, opts) {
|
||||
return this.base.download(downloadForEntry(location, path), opts);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.pathForEntry = function(entry) {
|
||||
OctoPrintFilesClient.prototype.pathForEntry = function (entry) {
|
||||
if (!entry || !entry.hasOwnProperty("parent") || entry.parent == undefined) {
|
||||
return "";
|
||||
}
|
||||
|
||||
var recursivePath = function(element, path) {
|
||||
if (element.hasOwnProperty("parent") && element.parent != undefined) {
|
||||
return recursivePath(element.parent, element.name + "/" + path);
|
||||
}
|
||||
var recursivePath = function (element, path) {
|
||||
if (element.hasOwnProperty("parent") && element.parent != undefined) {
|
||||
return recursivePath(element.parent, element.name + "/" + path);
|
||||
}
|
||||
|
||||
return path;
|
||||
return path;
|
||||
};
|
||||
|
||||
return recursivePath(entry.parent, entry.name);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.entryForPath = function(path, root) {
|
||||
OctoPrintFilesClient.prototype.entryForPath = function (path, root) {
|
||||
if (_.isArray(root)) {
|
||||
root = {children: root};
|
||||
}
|
||||
|
||||
var recursiveSearch = function(path, entry) {
|
||||
var recursiveSearch = function (path, entry) {
|
||||
if (path.length == 0) {
|
||||
return entry;
|
||||
}
|
||||
@@ -176,15 +198,19 @@
|
||||
return recursiveSearch(path.split("/"), root);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.pathForElement = function(element) {
|
||||
OctoPrintFilesClient.prototype.pathForElement = function (element) {
|
||||
// TODO Remove in 1.4.x
|
||||
log.warn("pathForElement has been renamed to pathForEntry, please use that instead");
|
||||
log.warn(
|
||||
"pathForElement has been renamed to pathForEntry, please use that instead"
|
||||
);
|
||||
return this.pathForEntry(element);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.elementByPath = function(location, startElement) {
|
||||
OctoPrintFilesClient.prototype.elementByPath = function (location, startElement) {
|
||||
// TODO Remove in 1.4.x
|
||||
log.warn("elementByPath has been renamed to entryForPath, please use that instead");
|
||||
log.warn(
|
||||
"elementByPath has been renamed to entryForPath, please use that instead"
|
||||
);
|
||||
return this.entryForPath(location, startElement);
|
||||
};
|
||||
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var url = "api/job";
|
||||
|
||||
var OctoPrintJobClient = function(base) {
|
||||
var OctoPrintJobClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintJobClient.prototype.issueCommand = function(command, payload, opts) {
|
||||
OctoPrintJobClient.prototype.issueCommand = function (command, payload, opts) {
|
||||
if (arguments.length == 2) {
|
||||
opts = payload;
|
||||
payload = {};
|
||||
@@ -20,31 +20,31 @@
|
||||
return this.base.issueCommand(url, command, payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintJobClient.prototype.get = function(opts) {
|
||||
OctoPrintJobClient.prototype.get = function (opts) {
|
||||
return OctoPrint.get(url, opts);
|
||||
};
|
||||
|
||||
OctoPrintJobClient.prototype.start = function(opts) {
|
||||
OctoPrintJobClient.prototype.start = function (opts) {
|
||||
return this.issueCommand("start", opts);
|
||||
};
|
||||
|
||||
OctoPrintJobClient.prototype.restart = function(opts) {
|
||||
OctoPrintJobClient.prototype.restart = function (opts) {
|
||||
return this.issueCommand("restart", opts);
|
||||
};
|
||||
|
||||
OctoPrintJobClient.prototype.pause = function(opts) {
|
||||
return this.issueCommand("pause", {"action": "pause"}, opts);
|
||||
OctoPrintJobClient.prototype.pause = function (opts) {
|
||||
return this.issueCommand("pause", {action: "pause"}, opts);
|
||||
};
|
||||
|
||||
OctoPrintJobClient.prototype.resume = function(opts) {
|
||||
return this.issueCommand("pause", {"action": "resume"}, opts)
|
||||
OctoPrintJobClient.prototype.resume = function (opts) {
|
||||
return this.issueCommand("pause", {action: "resume"}, opts);
|
||||
};
|
||||
|
||||
OctoPrintJobClient.prototype.togglePause = function(opts) {
|
||||
return this.issueCommand("pause", {"action": "toggle"}, opts);
|
||||
OctoPrintJobClient.prototype.togglePause = function (opts) {
|
||||
return this.issueCommand("pause", {action: "toggle"}, opts);
|
||||
};
|
||||
|
||||
OctoPrintJobClient.prototype.cancel = function(opts) {
|
||||
OctoPrintJobClient.prototype.cancel = function (opts) {
|
||||
return this.issueCommand("cancel", opts);
|
||||
};
|
||||
|
||||
|
||||
@@ -4,22 +4,22 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var url = "api/languages";
|
||||
|
||||
var OctoPrintLanguagesClient = function(base) {
|
||||
var OctoPrintLanguagesClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintLanguagesClient.prototype.list = function(opts) {
|
||||
OctoPrintLanguagesClient.prototype.list = function (opts) {
|
||||
return this.base.get(url, opts);
|
||||
};
|
||||
|
||||
OctoPrintLanguagesClient.prototype.upload = function(file) {
|
||||
OctoPrintLanguagesClient.prototype.upload = function (file) {
|
||||
return this.base.upload(url, file);
|
||||
};
|
||||
|
||||
OctoPrintLanguagesClient.prototype.delete = function(locale, pack, opts) {
|
||||
OctoPrintLanguagesClient.prototype.delete = function (locale, pack, opts) {
|
||||
var packUrl = url + "/" + locale + "/" + pack;
|
||||
return this.base.delete(packUrl, opts);
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var url = "api/printer";
|
||||
var printheadUrl = url + "/printhead";
|
||||
var toolUrl = url + "/tool";
|
||||
@@ -12,15 +12,23 @@
|
||||
var chamberUrl = url + "/chamber";
|
||||
var sdUrl = url + "/sd";
|
||||
|
||||
var OctoPrintPrinterClient = function(base) {
|
||||
var OctoPrintPrinterClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.issuePrintheadCommand = function (command, payload, opts) {
|
||||
OctoPrintPrinterClient.prototype.issuePrintheadCommand = function (
|
||||
command,
|
||||
payload,
|
||||
opts
|
||||
) {
|
||||
return this.base.issueCommand(printheadUrl, command, payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.issueToolCommand = function (command, payload, opts) {
|
||||
OctoPrintPrinterClient.prototype.issueToolCommand = function (
|
||||
command,
|
||||
payload,
|
||||
opts
|
||||
) {
|
||||
return this.base.issueCommand(toolUrl, command, payload, opts);
|
||||
};
|
||||
|
||||
@@ -28,7 +36,11 @@
|
||||
return this.base.issueCommand(bedUrl, command, payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.issueChamberCommand = function (command, payload, opts) {
|
||||
OctoPrintPrinterClient.prototype.issueChamberCommand = function (
|
||||
command,
|
||||
payload,
|
||||
opts
|
||||
) {
|
||||
return this.base.issueCommand(chamberUrl, command, payload, opts);
|
||||
};
|
||||
|
||||
@@ -150,7 +162,10 @@
|
||||
return this.issuePrintheadCommand("feedrate", payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.setToolTargetTemperatures = function (targets, opts) {
|
||||
OctoPrintPrinterClient.prototype.setToolTargetTemperatures = function (
|
||||
targets,
|
||||
opts
|
||||
) {
|
||||
targets = targets || {};
|
||||
|
||||
var payload = {
|
||||
@@ -160,7 +175,10 @@
|
||||
return this.issueToolCommand("target", payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.setToolTemperatureOffsets = function (offsets, opts) {
|
||||
OctoPrintPrinterClient.prototype.setToolTemperatureOffsets = function (
|
||||
offsets,
|
||||
opts
|
||||
) {
|
||||
offsets = offsets || {};
|
||||
|
||||
var payload = {
|
||||
@@ -220,7 +238,10 @@
|
||||
return this.issueBedCommand("offset", payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.setChamberTargetTemperature = function (target, opts) {
|
||||
OctoPrintPrinterClient.prototype.setChamberTargetTemperature = function (
|
||||
target,
|
||||
opts
|
||||
) {
|
||||
target = target || 0;
|
||||
|
||||
var payload = {
|
||||
@@ -230,7 +251,10 @@
|
||||
return this.issueChamberCommand("target", payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.setChamberTemperatureOffset = function (offset, opts) {
|
||||
OctoPrintPrinterClient.prototype.setChamberTemperatureOffset = function (
|
||||
offset,
|
||||
opts
|
||||
) {
|
||||
offset = offset || 0;
|
||||
|
||||
var payload = {
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient, global.$);
|
||||
}
|
||||
})(this, function(OctoPrintClient, $) {
|
||||
})(this, function (OctoPrintClient, $) {
|
||||
var url = "api/printerprofiles";
|
||||
|
||||
var profileUrl = function(profile) {
|
||||
var profileUrl = function (profile) {
|
||||
return url + "/" + profile;
|
||||
};
|
||||
|
||||
var OctoPrintPrinterProfileClient = function(base) {
|
||||
var OctoPrintPrinterProfileClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
return this.base.get(profileUrl(id), opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterProfileClient.prototype. update = function (id, profile, opts) {
|
||||
OctoPrintPrinterProfileClient.prototype.update = function (id, profile, opts) {
|
||||
profile = profile || {};
|
||||
|
||||
var data = {profile: profile};
|
||||
|
||||
@@ -4,37 +4,40 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient, global.$);
|
||||
}
|
||||
})(this, function(OctoPrintClient, $) {
|
||||
})(this, function (OctoPrintClient, $) {
|
||||
var url = "api/settings";
|
||||
var apiKeyUrl = url + "/apikey";
|
||||
|
||||
var OctoPrintSettingsClient = function(base) {
|
||||
var OctoPrintSettingsClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintSettingsClient.prototype.get = function(opts) {
|
||||
OctoPrintSettingsClient.prototype.get = function (opts) {
|
||||
return this.base.get(url, opts);
|
||||
};
|
||||
|
||||
OctoPrintSettingsClient.prototype.save = function(settings, opts) {
|
||||
OctoPrintSettingsClient.prototype.save = function (settings, opts) {
|
||||
settings = settings || {};
|
||||
return this.base.postJson(url, settings, opts);
|
||||
};
|
||||
|
||||
OctoPrintSettingsClient.prototype.getPluginSettings = function (plugin, opts) {
|
||||
return this.get(opts)
|
||||
.then(function (settings, statusText, request) {
|
||||
if (!settings.plugins || !settings.plugins[plugin]) {
|
||||
return $.Deferred()
|
||||
.reject(request, "dataerror", "No settings for plugin " + plugin)
|
||||
.promise();
|
||||
} else {
|
||||
return settings.plugins[plugin];
|
||||
}
|
||||
});
|
||||
return this.get(opts).then(function (settings, statusText, request) {
|
||||
if (!settings.plugins || !settings.plugins[plugin]) {
|
||||
return $.Deferred()
|
||||
.reject(request, "dataerror", "No settings for plugin " + plugin)
|
||||
.promise();
|
||||
} else {
|
||||
return settings.plugins[plugin];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
OctoPrintSettingsClient.prototype.savePluginSettings = function (plugin, settings, opts) {
|
||||
OctoPrintSettingsClient.prototype.savePluginSettings = function (
|
||||
plugin,
|
||||
settings,
|
||||
opts
|
||||
) {
|
||||
var data = {};
|
||||
data["plugins"] = {};
|
||||
data["plugins"][plugin] = settings;
|
||||
|
||||
@@ -4,44 +4,62 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var url = "api/slicing";
|
||||
|
||||
var slicerUrl = function(slicer) {
|
||||
var slicerUrl = function (slicer) {
|
||||
return url + "/" + slicer;
|
||||
};
|
||||
|
||||
var profileUrl = function(slicer, profileId) {
|
||||
var profileUrl = function (slicer, profileId) {
|
||||
return slicerUrl(slicer) + "/profiles/" + profileId;
|
||||
};
|
||||
|
||||
var OctoPrintSlicingClient = function(base) {
|
||||
var OctoPrintSlicingClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintSlicingClient.prototype.listAllSlicersAndProfiles = function(opts) {
|
||||
OctoPrintSlicingClient.prototype.listAllSlicersAndProfiles = function (opts) {
|
||||
return this.base.get(url, opts);
|
||||
};
|
||||
|
||||
OctoPrintSlicingClient.prototype.listProfilesForSlicer = function(slicer, opts) {
|
||||
OctoPrintSlicingClient.prototype.listProfilesForSlicer = function (slicer, opts) {
|
||||
return this.base.get(slicerUrl(slicer) + "/profiles", opts);
|
||||
};
|
||||
|
||||
OctoPrintSlicingClient.prototype.getProfileForSlicer = function(slicer, profileId, opts) {
|
||||
OctoPrintSlicingClient.prototype.getProfileForSlicer = function (
|
||||
slicer,
|
||||
profileId,
|
||||
opts
|
||||
) {
|
||||
return this.base.get(profileUrl(slicer, profileId), opts);
|
||||
};
|
||||
|
||||
OctoPrintSlicingClient.prototype.addProfileForSlicer = function(slicer, profileId, profile, opts) {
|
||||
OctoPrintSlicingClient.prototype.addProfileForSlicer = function (
|
||||
slicer,
|
||||
profileId,
|
||||
profile,
|
||||
opts
|
||||
) {
|
||||
profile = profile || {};
|
||||
return this.base.putJson(profileUrl(slicer, profileId), profile, opts);
|
||||
};
|
||||
|
||||
OctoPrintSlicingClient.prototype.updateProfileForSlicer = function(slicer, profileId, profile, opts) {
|
||||
OctoPrintSlicingClient.prototype.updateProfileForSlicer = function (
|
||||
slicer,
|
||||
profileId,
|
||||
profile,
|
||||
opts
|
||||
) {
|
||||
profile = profile || {};
|
||||
return this.base.patchJson(profileUrl(slicer, profileId), profile, opts);
|
||||
};
|
||||
|
||||
OctoPrintSlicingClient.prototype.deleteProfileForSlicer = function(slicer, profileId, opts) {
|
||||
OctoPrintSlicingClient.prototype.deleteProfileForSlicer = function (
|
||||
slicer,
|
||||
profileId,
|
||||
opts
|
||||
) {
|
||||
return this.base.delete(profileUrl(slicer, profileId), opts);
|
||||
};
|
||||
|
||||
|
||||
@@ -4,11 +4,10 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient, global.$, global._, global.SockJS);
|
||||
}
|
||||
})(this, function(OctoPrintClient, $, _, SockJS) {
|
||||
|
||||
})(this, function (OctoPrintClient, $, _, SockJS) {
|
||||
var normalClose = 1000;
|
||||
|
||||
var OctoPrintSocketClient = function(base) {
|
||||
var OctoPrintSocketClient = function (base) {
|
||||
var self = this;
|
||||
|
||||
this.base = base;
|
||||
@@ -30,30 +29,30 @@
|
||||
|
||||
this.connectTimeout = undefined;
|
||||
|
||||
this.onMessage("connected", function() {
|
||||
this.onMessage("connected", function () {
|
||||
// Make sure to clear connection timeout on connect
|
||||
if (self.connectTimeout) {
|
||||
clearTimeout(self.connectTimeout);
|
||||
self.connectTimeout = undefined;
|
||||
}
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.propagateMessage = function(event, data) {
|
||||
OctoPrintSocketClient.prototype.propagateMessage = function (event, data) {
|
||||
var start = new Date().getTime();
|
||||
|
||||
var eventObj = {event: event, data: data};
|
||||
|
||||
var catchAllHandlers = this.registeredHandlers["*"];
|
||||
if (catchAllHandlers && catchAllHandlers.length) {
|
||||
_.each(catchAllHandlers, function(handler) {
|
||||
_.each(catchAllHandlers, function (handler) {
|
||||
handler(eventObj);
|
||||
});
|
||||
}
|
||||
|
||||
var handlers = this.registeredHandlers[event];
|
||||
if (handlers && handlers.length) {
|
||||
_.each(handlers, function(handler) {
|
||||
_.each(handlers, function (handler) {
|
||||
handler(eventObj);
|
||||
});
|
||||
}
|
||||
@@ -62,7 +61,7 @@
|
||||
this.analyzeTiming(end - start);
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.analyzeTiming = function(measurement) {
|
||||
OctoPrintSocketClient.prototype.analyzeTiming = function (measurement) {
|
||||
while (this.rateLastMeasurements.length >= this.options.rateSlidingWindowSize) {
|
||||
this.rateLastMeasurements.shift();
|
||||
}
|
||||
@@ -80,7 +79,7 @@
|
||||
}
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.increaseRate = function() {
|
||||
OctoPrintSocketClient.prototype.increaseRate = function () {
|
||||
if (this.rateThrottleFactor <= 1) {
|
||||
this.rateThrottleFactor = 1;
|
||||
return;
|
||||
@@ -89,26 +88,26 @@
|
||||
this.sendThrottleFactor();
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.decreaseRate = function() {
|
||||
OctoPrintSocketClient.prototype.decreaseRate = function () {
|
||||
this.rateThrottleFactor++;
|
||||
this.sendThrottleFactor();
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.sendThrottleFactor = function() {
|
||||
OctoPrintSocketClient.prototype.sendThrottleFactor = function () {
|
||||
this.sendMessage("throttle", this.rateThrottleFactor);
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.sendAuth = function(userId, session) {
|
||||
OctoPrintSocketClient.prototype.sendAuth = function (userId, session) {
|
||||
this.sendMessage("auth", userId + ":" + session);
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.sendMessage = function(type, payload) {
|
||||
OctoPrintSocketClient.prototype.sendMessage = function (type, payload) {
|
||||
var data = {};
|
||||
data[type] = payload;
|
||||
this.socket.send(JSON.stringify(data));
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.connect = function(opts) {
|
||||
OctoPrintSocketClient.prototype.connect = function (opts) {
|
||||
opts = opts || {};
|
||||
|
||||
var self = this;
|
||||
@@ -126,13 +125,13 @@
|
||||
delete opts.connectTimeout;
|
||||
}
|
||||
|
||||
var onOpen = function() {
|
||||
var onOpen = function () {
|
||||
self.reconnecting = false;
|
||||
self.reconnectTrial = 0;
|
||||
self.onConnected();
|
||||
};
|
||||
|
||||
var onClose = function(e) {
|
||||
var onClose = function (e) {
|
||||
if (e.code === normalClose) {
|
||||
return;
|
||||
}
|
||||
@@ -145,15 +144,17 @@
|
||||
|
||||
if (self.reconnectTrial < self.options.timeouts.length) {
|
||||
var timeout = self.options.timeouts[self.reconnectTrial];
|
||||
setTimeout(function() { self.reconnect() }, timeout * 1000);
|
||||
setTimeout(function () {
|
||||
self.reconnect();
|
||||
}, timeout * 1000);
|
||||
self.reconnectTrial++;
|
||||
} else {
|
||||
self.onReconnectFailed();
|
||||
}
|
||||
};
|
||||
|
||||
var onMessage = function(msg) {
|
||||
_.each(msg.data, function(data, key) {
|
||||
var onMessage = function (msg) {
|
||||
_.each(msg.data, function (data, key) {
|
||||
self.propagateMessage(key, data);
|
||||
});
|
||||
};
|
||||
@@ -162,7 +163,7 @@
|
||||
clearTimeout(self.connectTimeout);
|
||||
}
|
||||
if (timeout > 0) {
|
||||
self.connectTimeout = setTimeout(function() {
|
||||
self.connectTimeout = setTimeout(function () {
|
||||
self.onConnectTimeout();
|
||||
}, timeout);
|
||||
}
|
||||
@@ -173,19 +174,19 @@
|
||||
self.socket.onmessage = onMessage;
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.reconnect = function() {
|
||||
OctoPrintSocketClient.prototype.reconnect = function () {
|
||||
this.disconnect();
|
||||
this.socket = undefined;
|
||||
this.connect();
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.disconnect = function() {
|
||||
OctoPrintSocketClient.prototype.disconnect = function () {
|
||||
if (this.socket !== undefined) {
|
||||
this.socket.close();
|
||||
}
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.onMessage = function(message, handler) {
|
||||
OctoPrintSocketClient.prototype.onMessage = function (message, handler) {
|
||||
if (!this.registeredHandlers.hasOwnProperty(message)) {
|
||||
this.registeredHandlers[message] = [];
|
||||
}
|
||||
@@ -193,16 +194,16 @@
|
||||
return this;
|
||||
};
|
||||
|
||||
OctoPrintSocketClient.prototype.onReconnectAttempt = function(trial) {};
|
||||
OctoPrintSocketClient.prototype.onReconnectFailed = function() {};
|
||||
OctoPrintSocketClient.prototype.onConnected = function() {};
|
||||
OctoPrintSocketClient.prototype.onDisconnected = function(code) {};
|
||||
OctoPrintSocketClient.prototype.onConnectTimeout = function() {};
|
||||
OctoPrintSocketClient.prototype.onReconnectAttempt = function (trial) {};
|
||||
OctoPrintSocketClient.prototype.onReconnectFailed = function () {};
|
||||
OctoPrintSocketClient.prototype.onConnected = function () {};
|
||||
OctoPrintSocketClient.prototype.onDisconnected = function (code) {};
|
||||
OctoPrintSocketClient.prototype.onConnectTimeout = function () {};
|
||||
|
||||
OctoPrintSocketClient.prototype.onRateTooLow = function(measured, minimum) {
|
||||
OctoPrintSocketClient.prototype.onRateTooLow = function (measured, minimum) {
|
||||
this.increaseRate();
|
||||
};
|
||||
OctoPrintSocketClient.prototype.onRateTooHigh = function(measured, maximum) {
|
||||
OctoPrintSocketClient.prototype.onRateTooHigh = function (measured, maximum) {
|
||||
this.decreaseRate();
|
||||
};
|
||||
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var url = "api/system";
|
||||
var commandUrl = "api/system/commands";
|
||||
|
||||
var OctoPrintSystemClient = function(base) {
|
||||
var OctoPrintSystemClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
|
||||
@@ -4,24 +4,24 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient, global.$);
|
||||
}
|
||||
})(this, function(OctoPrintClient, $) {
|
||||
})(this, function (OctoPrintClient, $) {
|
||||
var url = "api/timelapse";
|
||||
|
||||
var downloadUrl = "downloads/timelapse";
|
||||
|
||||
var timelapseUrl = function(filename) {
|
||||
var timelapseUrl = function (filename) {
|
||||
return url + "/" + filename;
|
||||
};
|
||||
|
||||
var timelapseDownloadUrl = function(filename) {
|
||||
var timelapseDownloadUrl = function (filename) {
|
||||
return downloadUrl + "/" + filename;
|
||||
};
|
||||
|
||||
var unrenderedTimelapseUrl = function(name) {
|
||||
var unrenderedTimelapseUrl = function (name) {
|
||||
return url + "/unrendered/" + name;
|
||||
};
|
||||
|
||||
var OctoPrintTimelapseClient = function(base) {
|
||||
var OctoPrintTimelapseClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
@@ -33,15 +33,19 @@
|
||||
return this.base.get(url, opts);
|
||||
};
|
||||
|
||||
OctoPrintTimelapseClient.prototype.list = function(opts) {
|
||||
OctoPrintTimelapseClient.prototype.list = function (opts) {
|
||||
var deferred = $.Deferred();
|
||||
|
||||
this.get(true, opts)
|
||||
.done(function (response, status, request) {
|
||||
deferred.resolve({
|
||||
rendered: response.files,
|
||||
unrendered: response.unrendered
|
||||
}, status, request);
|
||||
deferred.resolve(
|
||||
{
|
||||
rendered: response.files,
|
||||
unrendered: response.unrendered
|
||||
},
|
||||
status,
|
||||
request
|
||||
);
|
||||
})
|
||||
.fail(function () {
|
||||
deferred.reject.apply(null, arguments);
|
||||
@@ -86,11 +90,11 @@
|
||||
return this.base.delete(timelapseUrl(filename), opts);
|
||||
};
|
||||
|
||||
OctoPrintTimelapseClient.prototype.deleteUnrendered = function(name, opts) {
|
||||
OctoPrintTimelapseClient.prototype.deleteUnrendered = function (name, opts) {
|
||||
return this.base.delete(unrenderedTimelapseUrl(name), opts);
|
||||
};
|
||||
|
||||
OctoPrintTimelapseClient.prototype.renderUnrendered = function(name, opts) {
|
||||
OctoPrintTimelapseClient.prototype.renderUnrendered = function (name, opts) {
|
||||
return this.base.issueCommand(unrenderedTimelapseUrl(name), "render");
|
||||
};
|
||||
|
||||
|
||||
@@ -4,54 +4,101 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var deprecatedUserClient = function (deprecatedFct, newFct, fn) {
|
||||
return OctoPrintClient.deprecated("OctoPrint.users." + deprecatedFct, "OctoPrint.access.users." + newFct, fn);
|
||||
return OctoPrintClient.deprecated(
|
||||
"OctoPrint.users." + deprecatedFct,
|
||||
"OctoPrint.access.users." + newFct,
|
||||
fn
|
||||
);
|
||||
};
|
||||
|
||||
var OctoPrintUserClient = function(base) {
|
||||
var OctoPrintUserClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintUserClient.prototype.list = deprecatedUserClient("list", "list", function (opts) {
|
||||
OctoPrintUserClient.prototype.list = deprecatedUserClient("list", "list", function (
|
||||
opts
|
||||
) {
|
||||
return this.base.access.users.list(opts);
|
||||
});
|
||||
|
||||
OctoPrintUserClient.prototype.add = deprecatedUserClient("add", "add", function (user, opts) {
|
||||
OctoPrintUserClient.prototype.add = deprecatedUserClient("add", "add", function (
|
||||
user,
|
||||
opts
|
||||
) {
|
||||
return this.base.access.users.add(user, opts);
|
||||
});
|
||||
|
||||
OctoPrintUserClient.prototype.get = deprecatedUserClient("get", "get", function (name, opts) {
|
||||
OctoPrintUserClient.prototype.get = deprecatedUserClient("get", "get", function (
|
||||
name,
|
||||
opts
|
||||
) {
|
||||
return this.base.access.users.get(name, opts);
|
||||
});
|
||||
|
||||
OctoPrintUserClient.prototype.update = deprecatedUserClient("update", "update", function (name, active, admin, permissions, groups, opts) {
|
||||
return this.base.access.users.update(name, active, admin, permissions, groups, opts);
|
||||
});
|
||||
OctoPrintUserClient.prototype.update = deprecatedUserClient(
|
||||
"update",
|
||||
"update",
|
||||
function (name, active, admin, permissions, groups, opts) {
|
||||
return this.base.access.users.update(
|
||||
name,
|
||||
active,
|
||||
admin,
|
||||
permissions,
|
||||
groups,
|
||||
opts
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
OctoPrintUserClient.prototype.delete = deprecatedUserClient("delete", "delete", function (name, opts) {
|
||||
return this.base.access.users.delete(name, opts);
|
||||
});
|
||||
OctoPrintUserClient.prototype.delete = deprecatedUserClient(
|
||||
"delete",
|
||||
"delete",
|
||||
function (name, opts) {
|
||||
return this.base.access.users.delete(name, opts);
|
||||
}
|
||||
);
|
||||
|
||||
OctoPrintUserClient.prototype.changePassword = deprecatedUserClient("changePassword", "changePassword", function (name, password, opts) {
|
||||
return this.base.access.users.changePassword(name, password, opts);
|
||||
});
|
||||
OctoPrintUserClient.prototype.changePassword = deprecatedUserClient(
|
||||
"changePassword",
|
||||
"changePassword",
|
||||
function (name, password, opts) {
|
||||
return this.base.access.users.changePassword(name, password, opts);
|
||||
}
|
||||
);
|
||||
|
||||
OctoPrintUserClient.prototype.generateApiKey = deprecatedUserClient("generateApiKey", "generateApiKey", function (name, opts) {
|
||||
return this.base.access.users.generateApiKey(name, opts);
|
||||
});
|
||||
OctoPrintUserClient.prototype.generateApiKey = deprecatedUserClient(
|
||||
"generateApiKey",
|
||||
"generateApiKey",
|
||||
function (name, opts) {
|
||||
return this.base.access.users.generateApiKey(name, opts);
|
||||
}
|
||||
);
|
||||
|
||||
OctoPrintUserClient.prototype.resetApiKey = deprecatedUserClient("resetApiKey", "resetApiKey", function (name, opts) {
|
||||
return this.base.access.users.resetApiKey(name, opts);
|
||||
});
|
||||
OctoPrintUserClient.prototype.resetApiKey = deprecatedUserClient(
|
||||
"resetApiKey",
|
||||
"resetApiKey",
|
||||
function (name, opts) {
|
||||
return this.base.access.users.resetApiKey(name, opts);
|
||||
}
|
||||
);
|
||||
|
||||
OctoPrintUserClient.prototype.getSettings = deprecatedUserClient("getSettings", "getSettings", function (name, opts) {
|
||||
return this.base.access.users.getSettings(name, opts);
|
||||
});
|
||||
OctoPrintUserClient.prototype.getSettings = deprecatedUserClient(
|
||||
"getSettings",
|
||||
"getSettings",
|
||||
function (name, opts) {
|
||||
return this.base.access.users.getSettings(name, opts);
|
||||
}
|
||||
);
|
||||
|
||||
OctoPrintUserClient.prototype.saveSettings = deprecatedUserClient("saveSettings", "saveSettings", function (name, settings, opts) {
|
||||
return this.base.access.users.saveSettings(name, settings, opts);
|
||||
});
|
||||
OctoPrintUserClient.prototype.saveSettings = deprecatedUserClient(
|
||||
"saveSettings",
|
||||
"saveSettings",
|
||||
function (name, settings, opts) {
|
||||
return this.base.access.users.saveSettings(name, settings, opts);
|
||||
}
|
||||
);
|
||||
|
||||
OctoPrintClient.registerComponent("users", OctoPrintUserClient);
|
||||
return OctoPrintUserClient;
|
||||
|
||||
@@ -4,19 +4,19 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient, global.$);
|
||||
}
|
||||
})(this, function(OctoPrint, $) {
|
||||
})(this, function (OctoPrint, $) {
|
||||
var url = "api/util";
|
||||
var testUrl = url + "/test";
|
||||
|
||||
var OctoPrintUtilClient = function(base) {
|
||||
var OctoPrintUtilClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintUtilClient.prototype.test = function(command, parameters, opts) {
|
||||
OctoPrintUtilClient.prototype.test = function (command, parameters, opts) {
|
||||
return this.base.issueCommand(testUrl, command, parameters, opts);
|
||||
};
|
||||
|
||||
OctoPrintUtilClient.prototype.testPath = function(path, additional, opts) {
|
||||
OctoPrintUtilClient.prototype.testPath = function (path, additional, opts) {
|
||||
additional = additional || {};
|
||||
|
||||
var data = $.extend({}, additional);
|
||||
@@ -25,7 +25,7 @@
|
||||
return this.test("path", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintUtilClient.prototype.testExecutable = function(path, additional, opts) {
|
||||
OctoPrintUtilClient.prototype.testExecutable = function (path, additional, opts) {
|
||||
additional = additional || {};
|
||||
|
||||
var data = $.extend({}, additional);
|
||||
@@ -36,7 +36,7 @@
|
||||
return this.test("path", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintUtilClient.prototype.testUrl = function(url, additional, opts) {
|
||||
OctoPrintUtilClient.prototype.testUrl = function (url, additional, opts) {
|
||||
additional = additional || {};
|
||||
|
||||
var data = $.extend({}, additional);
|
||||
@@ -45,7 +45,7 @@
|
||||
return this.test("url", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintUtilClient.prototype.testServer = function(host, port, additional, opts) {
|
||||
OctoPrintUtilClient.prototype.testServer = function (host, port, additional, opts) {
|
||||
additional = additional || {};
|
||||
|
||||
var data = $.extend({}, additional);
|
||||
@@ -55,7 +55,7 @@
|
||||
return this.test("server", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintUtilClient.prototype.testResolution = function(name, additional, opts) {
|
||||
OctoPrintUtilClient.prototype.testResolution = function (name, additional, opts) {
|
||||
additional = additional || {};
|
||||
|
||||
var data = $.extend({}, additional);
|
||||
|
||||
@@ -4,18 +4,18 @@
|
||||
} else {
|
||||
factory(global.OctoPrintClient);
|
||||
}
|
||||
})(this, function(OctoPrintClient) {
|
||||
})(this, function (OctoPrintClient) {
|
||||
var url = "api/setup/wizard";
|
||||
|
||||
var OctoPrintWizardClient = function(base) {
|
||||
var OctoPrintWizardClient = function (base) {
|
||||
this.base = base;
|
||||
};
|
||||
|
||||
OctoPrintWizardClient.prototype.get = function(opts) {
|
||||
OctoPrintWizardClient.prototype.get = function (opts) {
|
||||
return this.base.get(url, opts);
|
||||
};
|
||||
|
||||
OctoPrintWizardClient.prototype.finish = function(handled, opts) {
|
||||
OctoPrintWizardClient.prototype.finish = function (handled, opts) {
|
||||
return this.base.postJson(url, {handled: handled || []}, opts);
|
||||
};
|
||||
|
||||
|
||||
@@ -19,40 +19,48 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
|
||||
self._safeModePopup = undefined;
|
||||
|
||||
self.increaseThrottle = function() {
|
||||
self.increaseThrottle = function () {
|
||||
self.setThrottle(self._throttleFactor + 1);
|
||||
};
|
||||
|
||||
self.decreaseThrottle = function() {
|
||||
self.decreaseThrottle = function () {
|
||||
if (self._throttleFactor <= 1) {
|
||||
return;
|
||||
}
|
||||
self.setThrottle(self._throttleFactor - 1);
|
||||
};
|
||||
|
||||
self.setThrottle = function(throttle) {
|
||||
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);
|
||||
log.debug(
|
||||
"DataUpdater: New SockJS throttle factor:",
|
||||
self._throttleFactor,
|
||||
" new processing limit:",
|
||||
self._baseProcessingLimit * self._throttleFactor
|
||||
);
|
||||
};
|
||||
|
||||
self._send = function(message, data) {
|
||||
self._send = function (message, data) {
|
||||
var payload = {};
|
||||
payload[message] = data;
|
||||
self._socket.send(JSON.stringify(payload));
|
||||
};
|
||||
|
||||
self.connect = function() {
|
||||
self.connect = function () {
|
||||
if (self._connectedDeferred) {
|
||||
self._connectedDeferred.reject("reconnect");
|
||||
}
|
||||
self._connectedDeferred = $.Deferred();
|
||||
OctoPrint.socket.connect({debug: !!SOCKJS_DEBUG, connectTimeout: SOCKJS_CONNECT_TIMEOUT});
|
||||
OctoPrint.socket.connect({
|
||||
debug: !!SOCKJS_DEBUG,
|
||||
connectTimeout: SOCKJS_CONNECT_TIMEOUT
|
||||
});
|
||||
return self._connectedDeferred.promise();
|
||||
};
|
||||
|
||||
self.reconnect = function() {
|
||||
self.reconnect = function () {
|
||||
if (self._connectedDeferred) {
|
||||
self._connectedDeferred.reject("reconnect");
|
||||
}
|
||||
@@ -61,14 +69,14 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
return self._connectedDeferred.promise();
|
||||
};
|
||||
|
||||
self.initialized = function() {
|
||||
self.initialized = function () {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.resolve();
|
||||
self._initializedDeferred = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
self._onReconnectAttempt = function(trial) {
|
||||
self._onReconnectAttempt = function (trial) {
|
||||
if (trial <= 0) {
|
||||
// Only consider it a real disconnect if the trial number has exceeded our threshold.
|
||||
return;
|
||||
@@ -78,8 +86,13 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
callViewModelsIf(
|
||||
self.allViewModels,
|
||||
"onServerDisconnect",
|
||||
function() { return !handled; },
|
||||
function(method) { var result = method(); handled = (result !== undefined && !result) || handled; }
|
||||
function () {
|
||||
return !handled;
|
||||
},
|
||||
function (method) {
|
||||
var result = method();
|
||||
handled = (result !== undefined && !result) || handled;
|
||||
}
|
||||
);
|
||||
|
||||
if (handled) {
|
||||
@@ -88,18 +101,25 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
|
||||
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."),
|
||||
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() {
|
||||
self._onReconnectFailed = function () {
|
||||
var handled = false;
|
||||
callViewModelsIf(
|
||||
self.allViewModels,
|
||||
"onServerDisconnect",
|
||||
function() { return !handled; },
|
||||
function(method) { var result = method(); handled = (result !== undefined && !result) || handled; }
|
||||
function () {
|
||||
return !handled;
|
||||
},
|
||||
function (method) {
|
||||
var result = method();
|
||||
handled = (result !== undefined && !result) || handled;
|
||||
}
|
||||
);
|
||||
|
||||
if (handled) {
|
||||
@@ -107,10 +127,14 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
}
|
||||
|
||||
$("#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."));
|
||||
$("#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) {
|
||||
self._onDisconnected = function (code) {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.reject();
|
||||
}
|
||||
@@ -121,13 +145,13 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
}
|
||||
};
|
||||
|
||||
self._onConnectTimeout = function() {
|
||||
self._onConnectTimeout = function () {
|
||||
if (self._connectedDeferred) {
|
||||
self._connectedDeferred.reject("timeout");
|
||||
}
|
||||
};
|
||||
|
||||
self._onConnectMessage = function(event) {
|
||||
self._onConnectMessage = function (event) {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.reject();
|
||||
}
|
||||
@@ -165,12 +189,14 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
self._connectedDeferred = undefined;
|
||||
}
|
||||
|
||||
self._ifInitialized(function() {
|
||||
self._ifInitialized(function () {
|
||||
// process safe mode
|
||||
if (self._safeModePopup) self._safeModePopup.remove();
|
||||
if (data["safe_mode"]) {
|
||||
// safe mode is active, let's inform the user
|
||||
log.info("❗ Safe mode is active. Third party plugins and language packs are disabled and cannot be enabled.");
|
||||
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");
|
||||
@@ -191,7 +217,12 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
|
||||
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)}),
|
||||
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
|
||||
});
|
||||
}
|
||||
@@ -211,8 +242,10 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
// if the version, the plugin hash or the config hash changed, we
|
||||
// want the user to reload the UI since it might be stale now
|
||||
var versionChanged = oldVersion !== VERSION;
|
||||
var pluginsChanged = oldPluginHash !== undefined && oldPluginHash !== self._pluginHash;
|
||||
var configChanged = oldConfigHash !== undefined && oldConfigHash !== self._configHash;
|
||||
var pluginsChanged =
|
||||
oldPluginHash !== undefined && oldPluginHash !== self._pluginHash;
|
||||
var configChanged =
|
||||
oldConfigHash !== undefined && oldConfigHash !== self._configHash;
|
||||
if (versionChanged || pluginsChanged || configChanged) {
|
||||
showReloadOverlay();
|
||||
}
|
||||
@@ -221,21 +254,27 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
});
|
||||
};
|
||||
|
||||
self._onHistoryData = function(event) {
|
||||
self._ifInitialized(function() {
|
||||
self._onHistoryData = function (event) {
|
||||
self._ifInitialized(function () {
|
||||
callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
|
||||
});
|
||||
};
|
||||
|
||||
self._onCurrentData = function(event) {
|
||||
self._ifInitialized(function() {
|
||||
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"])}));
|
||||
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", [
|
||||
@@ -247,20 +286,18 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
});
|
||||
};
|
||||
|
||||
self._onRenderProgress = function(event) {
|
||||
self._ifInitialized(function() {
|
||||
self._onRenderProgress = function (event) {
|
||||
self._ifInitialized(function () {
|
||||
var data = event.data;
|
||||
callViewModels(self.allViewModels, "onRenderProgress", [
|
||||
data["progress"]
|
||||
]);
|
||||
callViewModels(self.allViewModels, "onRenderProgress", [data["progress"]]);
|
||||
});
|
||||
};
|
||||
|
||||
self._printerErrorCancelNotification = undefined;
|
||||
self._printerErrorDisconnectNotification = undefined;
|
||||
self._printerResetNotification = undefined;
|
||||
self._onEvent = function(event) {
|
||||
self._ifInitialized(function() {
|
||||
self._onEvent = function (event) {
|
||||
self._ifInitialized(function () {
|
||||
var type = event.data["type"];
|
||||
var payload = event.data["payload"];
|
||||
|
||||
@@ -272,7 +309,12 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
}
|
||||
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)}),
|
||||
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
|
||||
});
|
||||
@@ -283,24 +325,44 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
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)});
|
||||
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)});
|
||||
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)});
|
||||
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)});
|
||||
text = _.sprintf(
|
||||
gettext(
|
||||
"There was an error while trying to start a print job. Error: %(error)s"
|
||||
),
|
||||
{error: _.escape(payload.error)}
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "autodetect": {
|
||||
@@ -309,7 +371,12 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
}
|
||||
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)});
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -319,20 +386,24 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
self._printerErrorDisconnectNotification.remove();
|
||||
}
|
||||
self._printerErrorDisconnectNotification = new PNotify({
|
||||
title: title,
|
||||
text: text,
|
||||
type: "error",
|
||||
hide: false
|
||||
title: title,
|
||||
text: text,
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
} else if (type === "PrinterReset") {
|
||||
var severity = undefined,
|
||||
text = undefined;
|
||||
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.");
|
||||
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.");
|
||||
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";
|
||||
}
|
||||
|
||||
@@ -348,55 +419,74 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
}
|
||||
|
||||
var legacyEventHandlers = {
|
||||
"UpdatedFiles": "onUpdatedFiles",
|
||||
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
|
||||
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
|
||||
"SlicingDone": "onSlicingDone",
|
||||
"SlicingCancelled": "onSlicingCancelled",
|
||||
"SlicingFailed": "onSlicingFailed"
|
||||
UpdatedFiles: "onUpdatedFiles",
|
||||
MetadataStatisticsUpdated: "onMetadataStatisticsUpdated",
|
||||
MetadataAnalysisFinished: "onMetadataAnalysisFinished",
|
||||
SlicingDone: "onSlicingDone",
|
||||
SlicingCancelled: "onSlicingCancelled",
|
||||
SlicingFailed: "onSlicingFailed"
|
||||
};
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
_.each(self.allViewModels, function (viewModel) {
|
||||
if (viewModel.hasOwnProperty("onEvent" + type)) {
|
||||
viewModel["onEvent" + type](payload);
|
||||
} else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
|
||||
} else if (
|
||||
legacyEventHandlers.hasOwnProperty(type) &&
|
||||
viewModel.hasOwnProperty(legacyEventHandlers[type])
|
||||
) {
|
||||
// there might still be code that uses the old callbacks, make sure those still get called
|
||||
// but log a warning
|
||||
log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + 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() {
|
||||
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._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._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");
|
||||
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");
|
||||
self._onDecreaseRate = function (measurement, maximum) {
|
||||
log.debug(
|
||||
"We are slow (" + measurement + " > " + maximum + "), reducing refresh rate"
|
||||
);
|
||||
OctoPrint.socket.decreaseRate();
|
||||
};
|
||||
|
||||
self._ifInitialized = function(callback) {
|
||||
self._ifInitialized = function (callback) {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.done(callback);
|
||||
} else {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+973
-789
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function AboutViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -6,33 +6,39 @@ $(function() {
|
||||
self.aboutContent = undefined;
|
||||
self.aboutTabs = undefined;
|
||||
|
||||
self.show = function() {
|
||||
self.show = function () {
|
||||
$("a:first", self.aboutTabs).tab("show");
|
||||
self.aboutContent.scrollTop(0);
|
||||
self.aboutDialog.modal({
|
||||
minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
|
||||
}).css({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
self.aboutDialog
|
||||
.modal({
|
||||
minHeight: function () {
|
||||
return Math.max($.fn.modal.defaults.maxHeight() - 80, 250);
|
||||
}
|
||||
})
|
||||
.css({
|
||||
"width": "auto",
|
||||
"margin-left": function () {
|
||||
return -($(this).width() / 2);
|
||||
}
|
||||
});
|
||||
return false;
|
||||
};
|
||||
|
||||
self.hide = function() {
|
||||
self.hide = function () {
|
||||
self.aboutDialog.modal("hide");
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
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() {
|
||||
$('a[data-toggle="tab"]', self.aboutTabs).on("show", function () {
|
||||
self.aboutContent.scrollTop(0);
|
||||
});
|
||||
};
|
||||
|
||||
self.showTab = function(tab) {
|
||||
self.showTab = function (tab) {
|
||||
$('a[href="#' + tab + '"]', self.aboutTabs).tab("show");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function AccessViewModel(parameters) {
|
||||
var access = this;
|
||||
|
||||
@@ -6,16 +6,18 @@ $(function() {
|
||||
|
||||
//~~ Users ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
access.users = (function() {
|
||||
access.users = (function () {
|
||||
var self = {};
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
"users",
|
||||
{
|
||||
"name": function(a, b) {
|
||||
name: function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase())
|
||||
return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase())
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
@@ -28,7 +30,7 @@ $(function() {
|
||||
|
||||
self.emptyUser = {name: "", active: false};
|
||||
|
||||
self.currentUser = ko.observable(self.emptyUser).extend({ notify: 'always' });
|
||||
self.currentUser = ko.observable(self.emptyUser).extend({notify: "always"});
|
||||
|
||||
self.editor = {
|
||||
name: ko.observable(undefined),
|
||||
@@ -36,16 +38,16 @@ $(function() {
|
||||
permissions: ko.observableArray([]),
|
||||
password: ko.observable(undefined),
|
||||
repeatedPassword: ko.observable(undefined),
|
||||
passwordMismatch: ko.pureComputed(function() {
|
||||
passwordMismatch: ko.pureComputed(function () {
|
||||
return self.editor.password() !== self.editor.repeatedPassword();
|
||||
}),
|
||||
apikey: ko.observable(undefined),
|
||||
active: ko.observable(undefined),
|
||||
permissionSelected: function(permission) {
|
||||
permissionSelected: function (permission) {
|
||||
var index = self.editor.permissions().indexOf(permission);
|
||||
return index >= 0;
|
||||
},
|
||||
togglePermission: function(permission) {
|
||||
togglePermission: function (permission) {
|
||||
var permissions = self.editor.permissions();
|
||||
var index = permissions.indexOf(permission);
|
||||
if (index < 0) {
|
||||
@@ -55,11 +57,11 @@ $(function() {
|
||||
}
|
||||
self.editor.permissions(permissions);
|
||||
},
|
||||
groupSelected: function(group) {
|
||||
groupSelected: function (group) {
|
||||
var index = self.editor.groups().indexOf(group);
|
||||
return index >= 0;
|
||||
},
|
||||
toggleGroup: function(group) {
|
||||
toggleGroup: function (group) {
|
||||
var groups = self.editor.groups();
|
||||
var index = groups.indexOf(group);
|
||||
if (index < 0) {
|
||||
@@ -69,22 +71,28 @@ $(function() {
|
||||
}
|
||||
self.editor.groups(groups);
|
||||
},
|
||||
joinedGroupPermissions: function(group) {
|
||||
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()
|
||||
&& (!self.editor.new() || (self.editor.password() && self.editor.password().trim() && !self.editor.passwordMismatch()));
|
||||
valid: ko.pureComputed(function () {
|
||||
return (
|
||||
self.editor.name() &&
|
||||
self.editor.name().trim() &&
|
||||
(!self.editor.new() ||
|
||||
(self.editor.password() &&
|
||||
self.editor.password().trim() &&
|
||||
!self.editor.passwordMismatch()))
|
||||
);
|
||||
})
|
||||
};
|
||||
|
||||
self.userEditorDialog = undefined;
|
||||
self.changePasswordDialog = undefined;
|
||||
|
||||
self.currentUser.subscribe(function(newValue) {
|
||||
self.currentUser.subscribe(function (newValue) {
|
||||
if (newValue === undefined) {
|
||||
self.editor.name(undefined);
|
||||
self.editor.groups(access.groups.defaults.slice(0));
|
||||
@@ -93,48 +101,57 @@ $(function() {
|
||||
self.editor.apikey(undefined);
|
||||
self.editor.header(gettext("Add user"));
|
||||
self.editor.new(true);
|
||||
self.editor.confirm = self.confirmAddUser
|
||||
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.header(
|
||||
_.sprintf(gettext('Edit user "%(name)s"'), {name: newValue.name})
|
||||
);
|
||||
self.editor.new(false);
|
||||
self.editor.confirm = self.confirmEditUser
|
||||
self.editor.confirm = self.confirmEditUser;
|
||||
}
|
||||
self.editor.password(undefined);
|
||||
self.editor.repeatedPassword(undefined);
|
||||
});
|
||||
|
||||
self.requestData = function() {
|
||||
self.requestData = function () {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
if (!access.loginState.hasPermissionKo(access.permissions.ADMIN)) return;
|
||||
|
||||
return OctoPrint.access.users.list()
|
||||
.done(self.fromResponse);
|
||||
return OctoPrint.access.users.list().done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.fromResponse = function (response) {
|
||||
self.listHelper.updateItems(response.users);
|
||||
};
|
||||
|
||||
self.showAddUserDialog = function() {
|
||||
self.showAddUserDialog = function () {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
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({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
$('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({
|
||||
"width": "auto",
|
||||
"margin-left": function () {
|
||||
return -($(this).width() / 2);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.confirmAddUser = function() {
|
||||
self.confirmAddUser = function () {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var user = {
|
||||
@@ -145,40 +162,54 @@ $(function() {
|
||||
active: self.editor.active()
|
||||
};
|
||||
|
||||
self.addUser(user)
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.userEditorDialog.modal("hide");
|
||||
});
|
||||
self.addUser(user).done(function () {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.userEditorDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.showEditUserDialog = function(user) {
|
||||
self.showEditUserDialog = function (user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var process = function(user) {
|
||||
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({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
$(
|
||||
'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({
|
||||
"width": "auto",
|
||||
"margin-left": function () {
|
||||
return -($(this).width() / 2);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
OctoPrint.users.get(user.name)
|
||||
.done(function(data) {
|
||||
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");
|
||||
.fail(function () {
|
||||
log.warn(
|
||||
"Could not fetch current user data, proceeding with client side data copy"
|
||||
);
|
||||
process(user);
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
self.confirmEditUser = function() {
|
||||
self.confirmEditUser = function () {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var user = self.currentUser();
|
||||
@@ -186,83 +217,86 @@ $(function() {
|
||||
user.groups = self.editor.groups();
|
||||
user.permissions = self.editor.permissions();
|
||||
|
||||
self.updateUser(user)
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.userEditorDialog.modal("hide");
|
||||
});
|
||||
self.updateUser(user).done(function () {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.userEditorDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.showChangePasswordDialog = function(user) {
|
||||
self.showChangePasswordDialog = function (user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.currentUser(user);
|
||||
self.changePasswordDialog.modal("show");
|
||||
};
|
||||
|
||||
self.confirmChangePassword = function() {
|
||||
self.confirmChangePassword = function () {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.updatePassword(self.currentUser().name, self.editor.password())
|
||||
.done(function() {
|
||||
self.updatePassword(self.currentUser().name, self.editor.password()).done(
|
||||
function () {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.changePasswordDialog.modal("hide");
|
||||
});
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
self.confirmGenerateApikey = function() {
|
||||
self.confirmGenerateApikey = function () {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.generateApikey(self.currentUser().name)
|
||||
.done(function(response) {
|
||||
self._updateApikey(response.apikey);
|
||||
});
|
||||
self.generateApikey(self.currentUser().name).done(function (response) {
|
||||
self._updateApikey(response.apikey);
|
||||
});
|
||||
};
|
||||
|
||||
self.copyApikey = function() {
|
||||
self.copyApikey = function () {
|
||||
copyToClipboard(self.editor.apikey());
|
||||
};
|
||||
|
||||
self._updateApikey = function(apikey) {
|
||||
self._updateApikey = function (apikey) {
|
||||
self.editor.apikey(apikey);
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.confirmDeleteApikey = function() {
|
||||
self.confirmDeleteApikey = function () {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.deleteApikey(self.currentUser().name)
|
||||
.done(function() {
|
||||
self._updateApikey(undefined);
|
||||
});
|
||||
self.deleteApikey(self.currentUser().name).done(function () {
|
||||
self._updateApikey(undefined);
|
||||
});
|
||||
};
|
||||
|
||||
//~~ Framework
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onStartup = function () {
|
||||
self.userEditorDialog = $("#settings-usersEditorDialog");
|
||||
self.changePasswordDialog = $("#settings-usersDialogChangePassword");
|
||||
};
|
||||
|
||||
//~~ API calls
|
||||
|
||||
self.addUser = function(user) {
|
||||
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.hasPermissionKo(access.permissions.ADMIN))
|
||||
return $.Deferred()
|
||||
.reject("You are not authorized to perform this action")
|
||||
.promise();
|
||||
|
||||
return OctoPrint.access.users.add(user)
|
||||
.done(self.fromResponse);
|
||||
return OctoPrint.access.users.add(user).done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.removeUser = function(user) {
|
||||
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.hasPermissionKo(access.permissions.ADMIN))
|
||||
return $.Deferred()
|
||||
.reject("You are not authorized to perform this action")
|
||||
.promise();
|
||||
|
||||
if (user.name === access.loginState.username()) {
|
||||
// we do not allow to delete ourselves
|
||||
@@ -271,42 +305,51 @@ $(function() {
|
||||
text: gettext("You may not delete your own account."),
|
||||
type: "error"
|
||||
});
|
||||
return $.Deferred().reject("You may not delete your own account").promise();
|
||||
return $.Deferred()
|
||||
.reject("You may not delete your own account")
|
||||
.promise();
|
||||
}
|
||||
|
||||
showConfirmationDialog({
|
||||
title: gettext("Are you sure?"),
|
||||
message: _.sprintf(gettext("You are about to delete the user \"%(name)s\"."), {name: user.name}),
|
||||
message: _.sprintf(
|
||||
gettext('You are about to delete the user "%(name)s".'),
|
||||
{name: user.name}
|
||||
),
|
||||
proceed: gettext("Delete"),
|
||||
onproceed: function() {
|
||||
OctoPrint.access.users.delete(user.name)
|
||||
.done(self.fromResponse);
|
||||
onproceed: function () {
|
||||
OctoPrint.access.users.delete(user.name).done(self.fromResponse);
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
self.updateUser = function(user) {
|
||||
self.updateUser = function (user) {
|
||||
if (!user) {
|
||||
throw OctoPrint.InvalidArgumentError("user must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.access.users.update(user.name, user.active, user.admin, user.permissions, user.groups)
|
||||
return OctoPrint.access.users
|
||||
.update(
|
||||
user.name,
|
||||
user.active,
|
||||
user.admin,
|
||||
user.permissions,
|
||||
user.groups
|
||||
)
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.updatePassword = function(username, password) {
|
||||
self.updatePassword = function (username, password) {
|
||||
return OctoPrint.access.users.changePassword(username, password);
|
||||
};
|
||||
|
||||
self.generateApikey = function(username) {
|
||||
return OctoPrint.access.users.generateApiKey(username)
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
});
|
||||
self.generateApikey = function (username) {
|
||||
return OctoPrint.access.users.generateApiKey(username).done(function () {
|
||||
self.requestData();
|
||||
});
|
||||
};
|
||||
|
||||
self.deleteApikey = function(username) {
|
||||
self.deleteApikey = function (username) {
|
||||
return OctoPrint.access.users.resetApiKey(username);
|
||||
};
|
||||
|
||||
@@ -315,16 +358,18 @@ $(function() {
|
||||
|
||||
//~~ Groups ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
access.groups = (function() {
|
||||
access.groups = (function () {
|
||||
var self = {};
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
"groups",
|
||||
{
|
||||
"name": function(a, b) {
|
||||
name: function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase())
|
||||
return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase())
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
@@ -350,11 +395,11 @@ $(function() {
|
||||
permissions: ko.observableArray([]),
|
||||
subgroups: ko.observableArray([]),
|
||||
default: ko.observable(false),
|
||||
permissionSelected: function(permission) {
|
||||
permissionSelected: function (permission) {
|
||||
var index = self.editor.permissions().indexOf(permission);
|
||||
return index >= 0;
|
||||
},
|
||||
togglePermission: function(permission) {
|
||||
togglePermission: function (permission) {
|
||||
var permissions = self.editor.permissions();
|
||||
var index = permissions.indexOf(permission);
|
||||
if (index < 0) {
|
||||
@@ -364,11 +409,11 @@ $(function() {
|
||||
}
|
||||
self.editor.permissions(permissions);
|
||||
},
|
||||
subgroupSelected: function(subgroup) {
|
||||
subgroupSelected: function (subgroup) {
|
||||
var index = self.editor.subgroups().indexOf(subgroup);
|
||||
return index >= 0;
|
||||
},
|
||||
toggleSubgroup: function(subgroup) {
|
||||
toggleSubgroup: function (subgroup) {
|
||||
var subgroups = self.editor.subgroups();
|
||||
var index = subgroups.indexOf(subgroup);
|
||||
if (index < 0) {
|
||||
@@ -378,13 +423,13 @@ $(function() {
|
||||
}
|
||||
self.editor.subgroups(subgroups);
|
||||
},
|
||||
joinedGroupPermissions: function(group) {
|
||||
joinedGroupPermissions: function (group) {
|
||||
return access.permissionList(group);
|
||||
},
|
||||
header: ko.observable(undefined),
|
||||
new: ko.observable(true),
|
||||
confirm: undefined,
|
||||
valid: ko.pureComputed(function() {
|
||||
valid: ko.pureComputed(function () {
|
||||
return self.editor.name() && self.editor.name().trim();
|
||||
})
|
||||
};
|
||||
@@ -392,25 +437,27 @@ $(function() {
|
||||
self.groupEditorDialog = undefined;
|
||||
|
||||
// used to delete all the groups before registering new ones
|
||||
self.groupsList.subscribe(function(oldValue) {
|
||||
if (oldValue === undefined || oldValue.length === 0)
|
||||
return;
|
||||
self.groupsList.subscribe(
|
||||
function (oldValue) {
|
||||
if (oldValue === undefined || oldValue.length === 0) return;
|
||||
|
||||
oldValue.forEach(function (p) {
|
||||
delete self[p.key.toUpperCase()];
|
||||
});
|
||||
}, null, "beforeChange");
|
||||
oldValue.forEach(function (p) {
|
||||
delete self[p.key.toUpperCase()];
|
||||
});
|
||||
},
|
||||
null,
|
||||
"beforeChange"
|
||||
);
|
||||
|
||||
// used to register new groups
|
||||
self.groupsList.subscribe(function(newValue) {
|
||||
if (newValue === undefined)
|
||||
return;
|
||||
self.groupsList.subscribe(function (newValue) {
|
||||
if (newValue === undefined) return;
|
||||
|
||||
newValue.forEach(function(g) {
|
||||
newValue.forEach(function (g) {
|
||||
var needs = [];
|
||||
g.permissions.forEach(function(p) {
|
||||
g.permissions.forEach(function (p) {
|
||||
for (var key in p.needs) {
|
||||
p.needs[key].forEach(function(value) {
|
||||
p.needs[key].forEach(function (value) {
|
||||
needs.push(access.permissions.need(key, value));
|
||||
});
|
||||
}
|
||||
@@ -423,7 +470,7 @@ $(function() {
|
||||
});
|
||||
});
|
||||
|
||||
self.registerGroup = function(name, group) {
|
||||
self.registerGroup = function (name, group) {
|
||||
Object.defineProperty(self, name, {
|
||||
value: group,
|
||||
enumerable: true,
|
||||
@@ -431,7 +478,7 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.currentGroup.subscribe(function(newValue) {
|
||||
self.currentGroup.subscribe(function (newValue) {
|
||||
if (newValue === undefined) {
|
||||
// group add
|
||||
self.editor.key(undefined);
|
||||
@@ -442,7 +489,7 @@ $(function() {
|
||||
self.editor.default(false);
|
||||
self.editor.header(gettext("Add group"));
|
||||
self.editor.new(true);
|
||||
self.editor.confirm = self.confirmAddGroup
|
||||
self.editor.confirm = self.confirmAddGroup;
|
||||
} else {
|
||||
// group update
|
||||
self.editor.key(newValue.key);
|
||||
@@ -451,21 +498,22 @@ $(function() {
|
||||
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.header(
|
||||
_.sprintf(gettext('Edit group "%(name)s"'), {name: newValue.name})
|
||||
);
|
||||
self.editor.new(false);
|
||||
self.editor.confirm = self.confirmEditGroup
|
||||
self.editor.confirm = self.confirmEditGroup;
|
||||
}
|
||||
});
|
||||
|
||||
self.requestData = function() {
|
||||
return OctoPrint.access.groups.list()
|
||||
.done(self.fromResponse);
|
||||
self.requestData = function () {
|
||||
return OctoPrint.access.groups.list().done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.fromResponse = function (response) {
|
||||
var lookup = {};
|
||||
var defaults = [];
|
||||
_.each(response.groups, function(group) {
|
||||
_.each(response.groups, function (group) {
|
||||
lookup[group.key] = group;
|
||||
if (group.default) {
|
||||
defaults.push(group.key);
|
||||
@@ -476,20 +524,32 @@ $(function() {
|
||||
self.listHelper.updateItems(response.groups);
|
||||
};
|
||||
|
||||
self.showAddGroupDialog = function() {
|
||||
self.showAddGroupDialog = function () {
|
||||
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({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
$('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({
|
||||
"width": "auto",
|
||||
"margin-left": function () {
|
||||
return -($(this).width() / 2);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.confirmAddGroup = function() {
|
||||
self.confirmAddGroup = function () {
|
||||
var group = {
|
||||
key: self.editor.name().toLowerCase().replace(/[^a-z0-9_ ]/g, "").replace(/ /g, "_"),
|
||||
key: self.editor
|
||||
.name()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_ ]/g, "")
|
||||
.replace(/ /g, "_"),
|
||||
name: self.editor.name(),
|
||||
description: self.editor.description(),
|
||||
permissions: self.editor.permissions(),
|
||||
@@ -497,28 +557,35 @@ $(function() {
|
||||
default: self.editor.default()
|
||||
};
|
||||
|
||||
self.addGroup(group)
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentGroup(undefined);
|
||||
self.groupEditorDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.showEditGroupDialog = function(group) {
|
||||
if (!group.changeable) return;
|
||||
|
||||
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({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
self.addGroup(group).done(function () {
|
||||
// close dialog
|
||||
self.currentGroup(undefined);
|
||||
self.groupEditorDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.confirmEditGroup = function() {
|
||||
self.showEditGroupDialog = function (group) {
|
||||
if (!group.changeable) return;
|
||||
|
||||
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({
|
||||
"width": "auto",
|
||||
"margin-left": function () {
|
||||
return -($(this).width() / 2);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.confirmEditGroup = function () {
|
||||
var group = self.currentGroup();
|
||||
|
||||
var data = {
|
||||
@@ -530,32 +597,30 @@ $(function() {
|
||||
default: self.editor.default()
|
||||
};
|
||||
|
||||
self.updateGroup(data)
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentGroup(undefined);
|
||||
self.groupEditorDialog.modal("hide");
|
||||
});
|
||||
self.updateGroup(data).done(function () {
|
||||
// close dialog
|
||||
self.currentGroup(undefined);
|
||||
self.groupEditorDialog.modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
//~~ Framework
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onStartup = function () {
|
||||
self.groupEditorDialog = $("#settings-groupsEditorDialog");
|
||||
};
|
||||
|
||||
//~~ API calls
|
||||
|
||||
self.addGroup = function(group) {
|
||||
self.addGroup = function (group) {
|
||||
if (!group) {
|
||||
throw OctoPrint.InvalidArgumentError("group must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.access.groups.add(group)
|
||||
.done(self.fromResponse);
|
||||
return OctoPrint.access.groups.add(group).done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.removeGroup = function(group) {
|
||||
self.removeGroup = function (group) {
|
||||
if (!group) {
|
||||
throw OctoPrint.InvalidArgumentError("group must be set");
|
||||
}
|
||||
@@ -564,24 +629,28 @@ $(function() {
|
||||
|
||||
showConfirmationDialog({
|
||||
title: gettext("Are you sure?"),
|
||||
message: _.sprintf(gettext("You are about to delete the group \"%(name)s\"."), {name: group.name}),
|
||||
message: _.sprintf(
|
||||
gettext('You are about to delete the group "%(name)s".'),
|
||||
{name: group.name}
|
||||
),
|
||||
proceed: gettext("Delete"),
|
||||
onproceed: function() {
|
||||
OctoPrint.access.groups.delete(group.key).done(function(response) {
|
||||
self.fromResponse(response);
|
||||
access.users.requestData();
|
||||
});
|
||||
onproceed: function () {
|
||||
OctoPrint.access.groups
|
||||
.delete(group.key)
|
||||
.done(function (response) {
|
||||
self.fromResponse(response);
|
||||
access.users.requestData();
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.updateGroup = function(group) {
|
||||
self.updateGroup = function (group) {
|
||||
if (!group) {
|
||||
throw OctoPrint.InvalidArgumentError("group must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.access.groups.update(group)
|
||||
.done(self.fromResponse);
|
||||
return OctoPrint.access.groups.update(group).done(self.fromResponse);
|
||||
};
|
||||
|
||||
return self;
|
||||
@@ -589,17 +658,21 @@ $(function() {
|
||||
|
||||
//~~ Permissions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
access.permissions = (function() {
|
||||
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.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) {
|
||||
var registerPermission = function (key, permission) {
|
||||
Object.defineProperty(self, key, {
|
||||
value: permission,
|
||||
enumerable: true,
|
||||
@@ -607,21 +680,21 @@ $(function() {
|
||||
});
|
||||
registeredPermissions.push(key);
|
||||
};
|
||||
var clearAllRegisteredPermissions = function() {
|
||||
_.each(registeredPermissions, function(key) {
|
||||
var clearAllRegisteredPermissions = function () {
|
||||
_.each(registeredPermissions, function (key) {
|
||||
delete self[key];
|
||||
});
|
||||
registeredPermissions = [];
|
||||
};
|
||||
|
||||
self.initialize = function() {
|
||||
self.initialize = function () {
|
||||
clearAllRegisteredPermissions();
|
||||
|
||||
var permissionList = [];
|
||||
var lookup = {};
|
||||
_.each(PERMISSIONS, function(permission) {
|
||||
_.each(PERMISSIONS, function (permission) {
|
||||
var needs = [];
|
||||
_.each(permission.needs, function(value, key) {
|
||||
_.each(permission.needs, function (value, key) {
|
||||
needs.push(self.need(key, value));
|
||||
});
|
||||
|
||||
@@ -645,7 +718,7 @@ $(function() {
|
||||
|
||||
//~~ helpers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
access.groupComparator = function(a, b) {
|
||||
access.groupComparator = function (a, b) {
|
||||
var nameA = a.name ? a.name.toUpperCase() : "";
|
||||
var nameB = b.name ? b.name.toUpperCase() : "";
|
||||
|
||||
@@ -658,7 +731,7 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
access.permissionComparator = function(a, b) {
|
||||
access.permissionComparator = function (a, b) {
|
||||
var nameA = a.name ? a.name.toUpperCase() : "";
|
||||
var nameB = b.name ? b.name.toUpperCase() : "";
|
||||
|
||||
@@ -678,68 +751,83 @@ $(function() {
|
||||
};
|
||||
|
||||
// Maps the group names into a comma separated list
|
||||
access.groupList = function(data) {
|
||||
if (data.groups === undefined)
|
||||
return "";
|
||||
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 });
|
||||
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 _.map(mappedGroups, function (g) {
|
||||
return g.name;
|
||||
}).join(", ");
|
||||
};
|
||||
|
||||
// Maps the sub group names into a comma separated list
|
||||
access.subgroupList = function(data) {
|
||||
if (data.subgroups === undefined)
|
||||
return "";
|
||||
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 });
|
||||
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 _.map(mappedGroups, function (g) {
|
||||
return g.name;
|
||||
}).join(", ");
|
||||
};
|
||||
|
||||
// Maps the permission names into a comma separated list
|
||||
access.permissionList = function(data) {
|
||||
if (!data || data.permissions === undefined)
|
||||
return "";
|
||||
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 });
|
||||
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 _.map(mappedPermissions, function (p) {
|
||||
return p.name;
|
||||
}).join(", ");
|
||||
};
|
||||
|
||||
//~~ API Calls
|
||||
access.onStartup = function() {
|
||||
access.onStartup = function () {
|
||||
access.groups.onStartup();
|
||||
access.users.onStartup();
|
||||
};
|
||||
|
||||
access.onServerConnect = function() {
|
||||
access.onServerConnect = function () {
|
||||
access.permissions.initialize();
|
||||
};
|
||||
|
||||
access.onServerReconnect = function() {
|
||||
access.onServerReconnect = function () {
|
||||
access.permissions.initialize();
|
||||
};
|
||||
|
||||
access.onUserPermissionsChanged = access.onUserLoggedIn = access.onUserLoggedOut = function(user) {
|
||||
access.onUserPermissionsChanged = access.onUserLoggedIn = access.onUserLoggedOut = function (
|
||||
user
|
||||
) {
|
||||
if (access.loginState.hasPermission(access.permissions.SETTINGS)) {
|
||||
access.groups.requestData()
|
||||
.done(function() {
|
||||
access.users.requestData();
|
||||
});
|
||||
access.groups.requestData().done(function () {
|
||||
access.users.requestData();
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
AccessViewModel,
|
||||
["loginStateViewModel"],
|
||||
[]
|
||||
]);
|
||||
OCTOPRINT_VIEWMODELS.push([AccessViewModel, ["loginStateViewModel"], []]);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
var save = {};
|
||||
|
||||
// Using the theme color (for the top bar), also recolor the favicon tentacle.
|
||||
@@ -16,9 +16,10 @@ $(function() {
|
||||
|
||||
// try to get the best quality ico possible; prefer svg, the apple-touch pngs are more difficult,
|
||||
// but all three of the others give a high-quality ico.
|
||||
var faviconUrl = document.querySelector("link[rel~='mask-icon-theme']").href
|
||||
|| link.href
|
||||
|| window.location.origin + "/favicon.ico";
|
||||
var faviconUrl =
|
||||
document.querySelector("link[rel~='mask-icon-theme']").href ||
|
||||
link.href ||
|
||||
window.location.origin + "/favicon.ico";
|
||||
|
||||
function onImageLoaded() {
|
||||
var icosize = 256;
|
||||
@@ -32,11 +33,19 @@ $(function() {
|
||||
function grayscale() {
|
||||
var imageData = context.getImageData(0, 0, canvas.width, canvas.height),
|
||||
pixels = imageData.data,
|
||||
i, l, r, g, b, a, luma;
|
||||
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; }
|
||||
if (a === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
r = pixels[i];
|
||||
g = pixels[i + 1];
|
||||
@@ -62,7 +71,7 @@ $(function() {
|
||||
context.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
if (save.colorName !== "default") {
|
||||
grayscale();
|
||||
colorize(save.colorName, .3);
|
||||
colorize(save.colorName, 0.3);
|
||||
}
|
||||
link.type = "image/x-icon";
|
||||
link.href = canvas.toDataURL();
|
||||
@@ -92,28 +101,22 @@ $(function() {
|
||||
self.colorIcon.subscribe(updateIcon);
|
||||
updateIcon();
|
||||
|
||||
self.brand = ko.pureComputed(function() {
|
||||
if (self.name())
|
||||
return self.name();
|
||||
else
|
||||
return gettext("OctoPrint");
|
||||
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.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.title = ko.pureComputed(function () {
|
||||
if (self.name()) return self.name() + " [" + gettext("OctoPrint") + "]";
|
||||
else return gettext("OctoPrint");
|
||||
});
|
||||
|
||||
self.theme_color = ko.pureComputed(function() {
|
||||
self.theme_color = ko.pureComputed(function () {
|
||||
switch (self.color()) {
|
||||
case "red":
|
||||
return "#bb645f";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function ConnectionViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -7,17 +7,17 @@ $(function() {
|
||||
self.printerProfiles = parameters[2];
|
||||
self.access = parameters[3];
|
||||
|
||||
self.printerProfiles.profiles.items.subscribe(function() {
|
||||
self.printerProfiles.profiles.items.subscribe(function () {
|
||||
var allProfiles = self.printerProfiles.profiles.items();
|
||||
|
||||
var printerOptions = [];
|
||||
_.each(allProfiles, function(profile) {
|
||||
_.each(allProfiles, function (profile) {
|
||||
printerOptions.push({id: profile.id, name: profile.name});
|
||||
});
|
||||
self.printerOptions(printerOptions);
|
||||
});
|
||||
|
||||
self.printerProfiles.currentProfile.subscribe(function() {
|
||||
self.printerProfiles.currentProfile.subscribe(function () {
|
||||
self.selectedPrinter(self.printerProfiles.currentProfile());
|
||||
});
|
||||
|
||||
@@ -38,27 +38,24 @@ $(function() {
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.buttonText = ko.pureComputed(function() {
|
||||
if (self.isErrorOrClosed())
|
||||
return gettext("Connect");
|
||||
else
|
||||
return gettext("Disconnect");
|
||||
self.buttonText = ko.pureComputed(function () {
|
||||
if (self.isErrorOrClosed()) return gettext("Connect");
|
||||
else return gettext("Disconnect");
|
||||
});
|
||||
|
||||
self.previousIsOperational = undefined;
|
||||
|
||||
self.refreshVisible = ko.observable(true);
|
||||
|
||||
self.requestData = function() {
|
||||
self.requestData = function () {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.CONNECTION)) {
|
||||
return;
|
||||
}
|
||||
|
||||
OctoPrint.connection.getSettings()
|
||||
.done(self.fromResponse);
|
||||
OctoPrint.connection.getSettings().done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.fromResponse = function (response) {
|
||||
var ports = response.options.ports;
|
||||
var baudrates = response.options.baudrates;
|
||||
var currentPort = response.current.port;
|
||||
@@ -97,15 +94,15 @@ $(function() {
|
||||
self.saveSettings(false);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self.fromHistoryData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self.fromCurrentData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self.openOrCloseOnStateChange = function(force) {
|
||||
self.openOrCloseOnStateChange = function (force) {
|
||||
if (!self._startupComplete && !force) return;
|
||||
|
||||
var connectionTab = $("#connection");
|
||||
@@ -118,7 +115,7 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self._processStateData = function (data) {
|
||||
self.previousIsOperational = self.isOperational();
|
||||
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
@@ -136,23 +133,21 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.connect = function() {
|
||||
self.connect = function () {
|
||||
if (self.isErrorOrClosed()) {
|
||||
var data = {
|
||||
"port": self.selectedPort() || "AUTO",
|
||||
"baudrate": self.selectedBaudrate() || 0,
|
||||
"printerProfile": self.selectedPrinter(),
|
||||
"autoconnect": self.settings.serial_autoconnect()
|
||||
port: self.selectedPort() || "AUTO",
|
||||
baudrate: self.selectedBaudrate() || 0,
|
||||
printerProfile: self.selectedPrinter(),
|
||||
autoconnect: self.settings.serial_autoconnect()
|
||||
};
|
||||
|
||||
if (self.saveSettings())
|
||||
data["save"] = true;
|
||||
if (self.saveSettings()) data["save"] = true;
|
||||
|
||||
OctoPrint.connection.connect(data)
|
||||
.done(function() {
|
||||
self.settings.requestData();
|
||||
self.settings.printerProfiles.requestData();
|
||||
});
|
||||
OctoPrint.connection.connect(data).done(function () {
|
||||
self.settings.requestData();
|
||||
self.settings.printerProfiles.requestData();
|
||||
});
|
||||
} else {
|
||||
if (!self.isPrinting() && !self.isPaused()) {
|
||||
self.requestData();
|
||||
@@ -160,58 +155,67 @@ $(function() {
|
||||
} 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?"),
|
||||
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() {
|
||||
onproceed: function () {
|
||||
self.requestData();
|
||||
OctoPrint.connection.disconnect();
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.onEventSettingsUpdated = function() {
|
||||
self.onEventSettingsUpdated = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventConnected = function() {
|
||||
self.onEventConnected = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventDisconnected = function() {
|
||||
self.onEventDisconnected = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onStartup = function () {
|
||||
var connectionTab = $("#connection");
|
||||
connectionTab.on("show", function() {
|
||||
connectionTab.on("show", function () {
|
||||
self.refreshVisible(true);
|
||||
});
|
||||
connectionTab.on("hide", function() {
|
||||
connectionTab.on("hide", function () {
|
||||
self.refreshVisible(false);
|
||||
});
|
||||
};
|
||||
|
||||
self.onStartupComplete = function() {
|
||||
self.onStartupComplete = function () {
|
||||
self.openOrCloseOnStateChange(true);
|
||||
};
|
||||
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: ConnectionViewModel,
|
||||
dependencies: ["loginStateViewModel", "settingsViewModel", "printerProfilesViewModel", "accessViewModel"],
|
||||
dependencies: [
|
||||
"loginStateViewModel",
|
||||
"settingsViewModel",
|
||||
"printerProfilesViewModel",
|
||||
"accessViewModel"
|
||||
],
|
||||
elements: ["#connection_wrapper"]
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function ControlViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -10,7 +10,7 @@ $(function() {
|
||||
return {
|
||||
name: ko.observable(),
|
||||
key: ko.observable()
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
@@ -46,13 +46,19 @@ $(function() {
|
||||
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;
|
||||
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.keycontrolActive() && self.keycontrolPossible();
|
||||
});
|
||||
|
||||
self.webcamRatioClass = ko.pureComputed(function() {
|
||||
self.webcamRatioClass = ko.pureComputed(function () {
|
||||
if (self.settings.webcam_streamRatio() == "4:3") {
|
||||
return "ratio43";
|
||||
} else {
|
||||
@@ -62,12 +68,16 @@ $(function() {
|
||||
|
||||
self.settings.printerProfiles.currentProfileData.subscribe(function () {
|
||||
self._updateExtruderCount();
|
||||
self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._updateExtruderCount);
|
||||
self.settings.printerProfiles
|
||||
.currentProfileData()
|
||||
.extruder.count.subscribe(self._updateExtruderCount);
|
||||
});
|
||||
self._updateExtruderCount = function () {
|
||||
var tools = [];
|
||||
|
||||
var numExtruders = self.settings.printerProfiles.currentProfileData().extruder.count();
|
||||
var numExtruders = self.settings.printerProfiles
|
||||
.currentProfileData()
|
||||
.extruder.count();
|
||||
if (numExtruders > 1) {
|
||||
// multiple extruders
|
||||
for (var extruder = 0; extruder < numExtruders; extruder++) {
|
||||
@@ -109,10 +119,10 @@ $(function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventRegisteredMessageReceived = function(payload) {
|
||||
self.onEventRegisteredMessageReceived = function (payload) {
|
||||
if (payload.key in self.feedbackControlLookup) {
|
||||
var outputs = self.feedbackControlLookup[payload.key];
|
||||
_.each(payload.outputs, function(value, key) {
|
||||
_.each(payload.outputs, function (value, key) {
|
||||
if (outputs.hasOwnProperty(key)) {
|
||||
outputs[key](value);
|
||||
}
|
||||
@@ -122,7 +132,7 @@ $(function() {
|
||||
|
||||
self.rerenderControls = function () {
|
||||
var allControls = self.controlsFromServer.concat(self.additionalControls);
|
||||
self.controls(self._processControls(allControls))
|
||||
self.controls(self._processControls(allControls));
|
||||
};
|
||||
|
||||
self.requestData = function () {
|
||||
@@ -130,10 +140,9 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
OctoPrint.control.getCustomControls()
|
||||
.done(function(response) {
|
||||
self._fromResponse(response);
|
||||
});
|
||||
OctoPrint.control.getCustomControls().done(function (response) {
|
||||
self._fromResponse(response);
|
||||
});
|
||||
};
|
||||
|
||||
self._fromResponse = function (response) {
|
||||
@@ -153,17 +162,32 @@ $(function() {
|
||||
return control;
|
||||
}
|
||||
|
||||
if (control.hasOwnProperty("template") && control.hasOwnProperty("key") && control.hasOwnProperty("template_key") && !control.hasOwnProperty("output")) {
|
||||
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;
|
||||
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.children = ko.observableArray(
|
||||
self._processControls(control.children)
|
||||
);
|
||||
if (
|
||||
!control.hasOwnProperty("layout") ||
|
||||
!(
|
||||
control.layout == "vertical" ||
|
||||
control.layout == "horizontal" ||
|
||||
control.layout == "horizontal_grid"
|
||||
)
|
||||
) {
|
||||
control.layout = "vertical";
|
||||
}
|
||||
|
||||
@@ -173,7 +197,7 @@ $(function() {
|
||||
}
|
||||
|
||||
if (control.hasOwnProperty("input")) {
|
||||
var attributeToInt = function(obj, key, def) {
|
||||
var attributeToInt = function (obj, key, def) {
|
||||
if (obj.hasOwnProperty(key)) {
|
||||
var val = obj[key];
|
||||
if (_.isNumber(val)) {
|
||||
@@ -191,21 +215,42 @@ $(function() {
|
||||
_.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);
|
||||
element.slider["max"] = attributeToInt(
|
||||
element.slider,
|
||||
"max",
|
||||
255
|
||||
);
|
||||
|
||||
// try defaultValue, default to min
|
||||
var defaultValue = attributeToInt(element, "default", element.slider.min);
|
||||
var defaultValue = attributeToInt(
|
||||
element,
|
||||
"default",
|
||||
element.slider.min
|
||||
);
|
||||
|
||||
// if default value is not within range of min and max, correct that
|
||||
if (!_.inRange(defaultValue, element.slider.min, element.slider.max)) {
|
||||
if (
|
||||
!_.inRange(
|
||||
defaultValue,
|
||||
element.slider.min,
|
||||
element.slider.max
|
||||
)
|
||||
) {
|
||||
// use bound closer to configured default value
|
||||
defaultValue = defaultValue < element.slider.min ? 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);
|
||||
element.value = ko.observable(
|
||||
element.hasOwnProperty("default")
|
||||
? element["default"]
|
||||
: undefined
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -228,7 +273,7 @@ $(function() {
|
||||
if (!_.isFunction(enabled)) {
|
||||
control.enabled = function (data) {
|
||||
return eval(enabled);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,7 +289,10 @@ $(function() {
|
||||
if (data.hasOwnProperty("enabled")) {
|
||||
return data.enabled(data);
|
||||
} else {
|
||||
return self.loginState.hasPermission(self.access.permissions.CONTROL) && self.isOperational();
|
||||
return (
|
||||
self.loginState.hasPermission(self.access.permissions.CONTROL) &&
|
||||
self.isOperational()
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -269,9 +317,15 @@ $(function() {
|
||||
};
|
||||
|
||||
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"]()) {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -292,22 +346,25 @@ $(function() {
|
||||
|
||||
rate = _.parseInt(self.feedRate());
|
||||
self.feedRateBusy(true);
|
||||
OctoPrint.printer.setFeedrate(rate)
|
||||
.done(function() {
|
||||
OctoPrint.printer
|
||||
.setFeedrate(rate)
|
||||
.done(function () {
|
||||
self.feedRate(undefined);
|
||||
})
|
||||
.always(function() {
|
||||
.always(function () {
|
||||
self.feedRateBusy(false);
|
||||
});
|
||||
};
|
||||
self.resetFeedRateDisplay = function() {
|
||||
self.resetFeedRateDisplay = function () {
|
||||
self.cancelFeedRateDisplayReset();
|
||||
self.feedRateResetter(setTimeout(function() {
|
||||
self.feedRate(undefined);
|
||||
self.feedRateResetter(undefined);
|
||||
}, 5000));
|
||||
self.feedRateResetter(
|
||||
setTimeout(function () {
|
||||
self.feedRate(undefined);
|
||||
self.feedRateResetter(undefined);
|
||||
}, 5000)
|
||||
);
|
||||
};
|
||||
self.cancelFeedRateDisplayReset = function() {
|
||||
self.cancelFeedRateDisplayReset = function () {
|
||||
var resetter = self.feedRateResetter();
|
||||
if (resetter) {
|
||||
clearTimeout(resetter);
|
||||
@@ -331,22 +388,25 @@ $(function() {
|
||||
|
||||
rate = _.parseInt(self.flowRate());
|
||||
self.flowRateBusy(true);
|
||||
OctoPrint.printer.setFlowrate(rate)
|
||||
.done(function() {
|
||||
OctoPrint.printer
|
||||
.setFlowrate(rate)
|
||||
.done(function () {
|
||||
self.flowRate(undefined);
|
||||
})
|
||||
.always(function() {
|
||||
.always(function () {
|
||||
self.flowRateBusy(false);
|
||||
});
|
||||
};
|
||||
self.resetFlowRateDisplay = function() {
|
||||
self.resetFlowRateDisplay = function () {
|
||||
self.cancelFlowRateDisplayReset();
|
||||
self.flowRateResetter(setTimeout(function() {
|
||||
self.flowRate(undefined);
|
||||
self.flowRateResetter(undefined);
|
||||
}, 5000));
|
||||
self.flowRateResetter(
|
||||
setTimeout(function () {
|
||||
self.flowRate(undefined);
|
||||
self.flowRateResetter(undefined);
|
||||
}, 5000)
|
||||
);
|
||||
};
|
||||
self.cancelFlowRateDisplayReset = function() {
|
||||
self.cancelFlowRateDisplayReset = function () {
|
||||
var resetter = self.flowRateResetter();
|
||||
if (resetter) {
|
||||
clearTimeout(resetter);
|
||||
@@ -371,7 +431,10 @@ $(function() {
|
||||
var parameters = {};
|
||||
if (command.hasOwnProperty("input")) {
|
||||
_.each(command.input, function (input) {
|
||||
if (!input.hasOwnProperty("parameter") || !input.hasOwnProperty("value")) {
|
||||
if (
|
||||
!input.hasOwnProperty("parameter") ||
|
||||
!input.hasOwnProperty("value")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -385,7 +448,11 @@ $(function() {
|
||||
} else if (command.hasOwnProperty("script")) {
|
||||
var script = command.script;
|
||||
var context = command.context || {};
|
||||
OctoPrint.control.sendGcodeScriptWithParameters(script, context, parameters);
|
||||
OctoPrint.control.sendGcodeScriptWithParameters(
|
||||
script,
|
||||
context,
|
||||
parameters
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -413,11 +480,11 @@ $(function() {
|
||||
return span + " " + offset;
|
||||
};
|
||||
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self._disableWebcam = function() {
|
||||
self._disableWebcam = function () {
|
||||
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
|
||||
// more load by the constant connection creation than by the actual webcam stream
|
||||
|
||||
@@ -434,8 +501,11 @@ $(function() {
|
||||
}, timeout * 1000);
|
||||
};
|
||||
|
||||
self._enableWebcam = function() {
|
||||
if (OctoPrint.coreui.selectedTab != "#control" || !OctoPrint.coreui.browserTabVisible) {
|
||||
self._enableWebcam = function () {
|
||||
if (
|
||||
OctoPrint.coreui.selectedTab != "#control" ||
|
||||
!OctoPrint.coreui.browserTabVisible
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -454,7 +524,7 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.onWebcamLoaded = function() {
|
||||
self.onWebcamLoaded = function () {
|
||||
if (self.webcamLoaded()) return;
|
||||
|
||||
log.debug("Webcam stream loaded");
|
||||
@@ -462,7 +532,7 @@ $(function() {
|
||||
self.webcamError(false);
|
||||
};
|
||||
|
||||
self.onWebcamErrored = function() {
|
||||
self.onWebcamErrored = function () {
|
||||
log.debug("Webcam stream failed to load/disabled");
|
||||
self.webcamLoaded(false);
|
||||
self.webcamError(true);
|
||||
@@ -476,7 +546,7 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.onBrowserTabVisibilityChange = function(status) {
|
||||
self.onBrowserTabVisibilityChange = function (status) {
|
||||
if (status) {
|
||||
self._enableWebcam();
|
||||
} else {
|
||||
@@ -486,7 +556,7 @@ $(function() {
|
||||
|
||||
self.onAllBound = function (allViewModels) {
|
||||
var additionalControls = [];
|
||||
callViewModels(allViewModels, "getAdditionalControls", function(method) {
|
||||
callViewModels(allViewModels, "getAdditionalControls", function (method) {
|
||||
additionalControls = additionalControls.concat(method());
|
||||
});
|
||||
if (additionalControls.length > 0) {
|
||||
@@ -603,11 +673,11 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.stripDistanceDecimal = function(distance) {
|
||||
self.stripDistanceDecimal = function (distance) {
|
||||
return distance.toString().replace(".", "");
|
||||
};
|
||||
|
||||
self._switchToMjpgWebcam = function() {
|
||||
self._switchToMjpgWebcam = function () {
|
||||
var webcamImage = $("#webcam_image");
|
||||
var currentSrc = webcamImage.attr("src");
|
||||
|
||||
@@ -632,15 +702,14 @@ $(function() {
|
||||
self.webcamHlsEnabled(false);
|
||||
self.webcamMjpgEnabled(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self._switchToHlsWebcam = function() {
|
||||
var video = document.getElementById('webcam_hls');
|
||||
self._switchToHlsWebcam = function () {
|
||||
var video = document.getElementById("webcam_hls");
|
||||
|
||||
if (video.canPlayType('application/vnd.apple.mpegurl')) {
|
||||
if (video.canPlayType("application/vnd.apple.mpegurl")) {
|
||||
video.src = self.settings.webcam_streamUrl();
|
||||
}
|
||||
else if (Hls.isSupported()) {
|
||||
} else if (Hls.isSupported()) {
|
||||
var hls = new Hls();
|
||||
hls.loadSource(self.settings.webcam_streamUrl());
|
||||
hls.attachMedia(video);
|
||||
@@ -648,7 +717,7 @@ $(function() {
|
||||
|
||||
self.webcamMjpgEnabled(false);
|
||||
self.webcamHlsEnabled(true);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function LoginStateViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -24,7 +24,7 @@ $(function() {
|
||||
|
||||
self.externalAddressNotification = undefined;
|
||||
|
||||
self.userMenuText = ko.pureComputed(function() {
|
||||
self.userMenuText = ko.pureComputed(function () {
|
||||
if (self.loggedIn()) {
|
||||
return self.username();
|
||||
} else {
|
||||
@@ -32,51 +32,60 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
self.userMenuTitle = ko.pureComputed(function() {
|
||||
self.userMenuTitle = ko.pureComputed(function () {
|
||||
if (self.loggedIn()) {
|
||||
return _.sprintf(gettext("Logged in as %(name)s"), {name: _.escape(self.username())});
|
||||
return _.sprintf(gettext("Logged in as %(name)s"), {
|
||||
name: _.escape(self.username())
|
||||
});
|
||||
} else {
|
||||
return gettext("Login");
|
||||
}
|
||||
});
|
||||
|
||||
self.logoutSupported = ko.pureComputed(function() {
|
||||
self.logoutSupported = ko.pureComputed(function () {
|
||||
var mechanism = self.currentLoginMechanism();
|
||||
return !(mechanism === "apikey" || mechanism === "authheader");
|
||||
});
|
||||
self.logoutTooltip = ko.pureComputed(function() {
|
||||
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")
|
||||
}
|
||||
return _.sprintf(gettext("Logout not supported for %(method)s, please close the browser instead"), {method: methodMap[mechanism]});
|
||||
};
|
||||
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() {
|
||||
self.reloadUser = function () {
|
||||
if (self.currentUser() === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
return OctoPrint.access.users.get(self.currentUser().name)
|
||||
return OctoPrint.access.users
|
||||
.get(self.currentUser().name)
|
||||
.done(self.updateCurrentUserData);
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
return OctoPrint.browser.passiveLogin()
|
||||
self.requestData = function () {
|
||||
return OctoPrint.browser
|
||||
.passiveLogin()
|
||||
.done(self.fromResponse)
|
||||
.fail(function() {
|
||||
.fail(function () {
|
||||
// something went very wrong, still, proceed
|
||||
self.fromResponse();
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
var process = function() {
|
||||
self.fromResponse = function (response) {
|
||||
var process = function () {
|
||||
var currentLoggedIn = self.loggedIn();
|
||||
var currentNeeds = self.userneeds();
|
||||
if (response && response.name) {
|
||||
@@ -96,23 +105,31 @@ $(function() {
|
||||
}
|
||||
|
||||
// Show warning if connecting from what seems to be an external IP address, unless ignored
|
||||
var ignorePublicAddressWarning = localStorage["loginState.ignorePublicAddressWarning"];
|
||||
var ignorePublicAddressWarning =
|
||||
localStorage["loginState.ignorePublicAddressWarning"];
|
||||
if (ignorePublicAddressWarning === undefined) {
|
||||
ignorePublicAddressWarning = false;
|
||||
} else {
|
||||
ignorePublicAddressWarning = JSON.parse(ignorePublicAddressWarning);
|
||||
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/"});
|
||||
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();
|
||||
@@ -125,26 +142,30 @@ $(function() {
|
||||
type: "error",
|
||||
confirm: {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Ignore"),
|
||||
addClass: "btn btn-danger",
|
||||
click: function(notice) {
|
||||
notice.remove();
|
||||
localStorage["loginState.ignorePublicAddressWarning"] = JSON.stringify(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();
|
||||
}
|
||||
}
|
||||
}, {
|
||||
text: gettext("Later"),
|
||||
addClass: "btn btn-primary",
|
||||
click: function(notice) {
|
||||
notice.remove();
|
||||
}
|
||||
}]
|
||||
]
|
||||
},
|
||||
buttons: {
|
||||
sticker: false
|
||||
}
|
||||
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
if (response._login_mechanism) {
|
||||
@@ -174,7 +195,7 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.updateCurrentUserData = function(data) {
|
||||
self.updateCurrentUserData = function (data) {
|
||||
if (data) {
|
||||
self.userneeds(data.needs);
|
||||
} else {
|
||||
@@ -198,18 +219,22 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.login = function(u, p, r, notifications) {
|
||||
self.login = function (u, p, r, notifications) {
|
||||
var username = u || self.loginUser();
|
||||
var password = p || self.loginPass();
|
||||
var remember = (r !== undefined ? r : self.loginRemember());
|
||||
var remember = r !== undefined ? r : self.loginRemember();
|
||||
notifications = notifications !== false;
|
||||
|
||||
return OctoPrint.browser.login(username, password, remember)
|
||||
.done(function(response) {
|
||||
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)}),
|
||||
text: _.sprintf(
|
||||
gettext('You are now logged in as "%(username)s"'),
|
||||
{username: _.escape(response.name)}
|
||||
),
|
||||
type: "success"
|
||||
});
|
||||
}
|
||||
@@ -220,19 +245,25 @@ $(function() {
|
||||
self.loginRemember(false);
|
||||
|
||||
if (history && history.replaceState) {
|
||||
history.replaceState({success: true}, document.title, window.location.pathname);
|
||||
history.replaceState(
|
||||
{success: true},
|
||||
document.title,
|
||||
window.location.pathname
|
||||
);
|
||||
}
|
||||
})
|
||||
.fail(function(response) {
|
||||
.fail(function (response) {
|
||||
if (!notifications) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch(response.status) {
|
||||
switch (response.status) {
|
||||
case 403: {
|
||||
new PNotify({
|
||||
title: gettext("Login failed"),
|
||||
text: gettext("User unknown, wrong password or account deactivated"),
|
||||
text: gettext(
|
||||
"User unknown, wrong password or account deactivated"
|
||||
),
|
||||
type: "error"
|
||||
});
|
||||
break;
|
||||
@@ -242,7 +273,7 @@ $(function() {
|
||||
};
|
||||
|
||||
var _logoutInProgress = false;
|
||||
self.logout = function(target, event) {
|
||||
self.logout = function (target, event) {
|
||||
if (!self.logoutSupported()) {
|
||||
event.stopPropagation();
|
||||
return;
|
||||
@@ -250,29 +281,34 @@ $(function() {
|
||||
|
||||
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"});
|
||||
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) {
|
||||
.fail(function (error) {
|
||||
if (error && error.status === 403) {
|
||||
self.fromResponse(false);
|
||||
self.fromResponse(false);
|
||||
}
|
||||
})
|
||||
.always(function() {
|
||||
.always(function () {
|
||||
_logoutInProgress = false;
|
||||
});
|
||||
};
|
||||
|
||||
self.prepareLogin = function(data, event) {
|
||||
if(event && event.preventDefault) {
|
||||
self.prepareLogin = function (data, event) {
|
||||
if (event && event.preventDefault) {
|
||||
event.preventDefault();
|
||||
}
|
||||
self.login();
|
||||
};
|
||||
|
||||
self.onDataUpdaterReauthRequired = function(reason) {
|
||||
self.onDataUpdaterReauthRequired = function (reason) {
|
||||
if (reason === "logout" || reason === "removed") {
|
||||
self.logout();
|
||||
} else {
|
||||
@@ -280,13 +316,13 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.onAllBound = function(allViewModels) {
|
||||
self.onAllBound = function (allViewModels) {
|
||||
self.allViewModels = allViewModels;
|
||||
self.startupDeferred.resolve();
|
||||
self.startupDeferred = undefined;
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onStartup = function () {
|
||||
self.elementUsernameInput = $("#login_user");
|
||||
self.elementPasswordInput = $("#login_pass");
|
||||
self.elementLoginButton = $("#login_button");
|
||||
@@ -294,38 +330,48 @@ $(function() {
|
||||
var toggle = $("li.dropdown#navbar_login");
|
||||
var button = $("a", toggle);
|
||||
|
||||
button.on("click", function(e) {
|
||||
button.on("click", function (e) {
|
||||
$(this).parent().toggleClass("open");
|
||||
});
|
||||
|
||||
$("body").on("click", function(e) {
|
||||
$("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 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;
|
||||
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() {
|
||||
if (
|
||||
self.elementUsernameInput &&
|
||||
self.elementUsernameInput.length &&
|
||||
self.elementLoginButton &&
|
||||
self.elementLoginButton.length
|
||||
) {
|
||||
self.elementLoginButton.blur(function () {
|
||||
self.elementUsernameInput.focus();
|
||||
})
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
self.hasPermission = function(permission) {
|
||||
self.hasPermission = function (permission) {
|
||||
/**
|
||||
* Checks if the currently logged in user has a specific permission.
|
||||
*
|
||||
@@ -340,21 +386,23 @@ $(function() {
|
||||
* @type {boolean}
|
||||
*/
|
||||
var userneeds = self.userneeds();
|
||||
if (userneeds === undefined || permission === undefined)
|
||||
return false;
|
||||
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);
|
||||
});
|
||||
return _.any(permission, function (need) {
|
||||
return (
|
||||
_.has(userneeds, need.method) &&
|
||||
_.all(need.value, function (value) {
|
||||
return _.contains(userneeds[need.method], value);
|
||||
})
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
self.hasAnyPermission = function() {
|
||||
self.hasAnyPermission = function () {
|
||||
/**
|
||||
* Checks if the currently logged in user has any of the specified permissions.
|
||||
*
|
||||
@@ -368,13 +416,13 @@ $(function() {
|
||||
* @type {boolean}
|
||||
*/
|
||||
var result = false;
|
||||
_.each(arguments, function(permission) {
|
||||
_.each(arguments, function (permission) {
|
||||
result = result || self.hasPermission(permission);
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
self.hasAllPermissions = function() {
|
||||
self.hasAllPermissions = function () {
|
||||
/**
|
||||
* Checks if the currently logged in user has all of the specified permissions.
|
||||
*
|
||||
@@ -388,37 +436,41 @@ $(function() {
|
||||
* @type {boolean}
|
||||
*/
|
||||
var result = true;
|
||||
_.each(arguments, function(permission) {
|
||||
_.each(arguments, function (permission) {
|
||||
result = result && self.hasPermission(permission);
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
self.hasPermissionKo = function(permission) {
|
||||
self.hasPermissionKo = function (permission) {
|
||||
/**
|
||||
* Knockout wrapper for hasPermission
|
||||
*/
|
||||
return ko.pureComputed(function() {
|
||||
return self.hasPermission(permission);
|
||||
}).extend({ notify: "always" });
|
||||
return ko
|
||||
.pureComputed(function () {
|
||||
return self.hasPermission(permission);
|
||||
})
|
||||
.extend({notify: "always"});
|
||||
};
|
||||
|
||||
self.hasAnyPermissionKo = function() {
|
||||
self.hasAnyPermissionKo = function () {
|
||||
/**
|
||||
Knockout wrapper for hasAnyPermission
|
||||
*/
|
||||
var permissions = arguments;
|
||||
return ko.pureComputed(function() {
|
||||
return self.hasAnyPermission.apply(null, permissions);
|
||||
}).extend({ notify: "always" });
|
||||
return ko
|
||||
.pureComputed(function () {
|
||||
return self.hasAnyPermission.apply(null, permissions);
|
||||
})
|
||||
.extend({notify: "always"});
|
||||
};
|
||||
|
||||
self.hasAllPermissionsKo = function() {
|
||||
self.hasAllPermissionsKo = function () {
|
||||
/**
|
||||
* Knockout wrapper for hasAllPermissions
|
||||
*/
|
||||
var permissions = arguments;
|
||||
return ko.pureComputed(function() {
|
||||
return ko.pureComputed(function () {
|
||||
return self.hasAllPermissions.apply(null, permissions);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -3,29 +3,38 @@
|
||||
* OctoPrint web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
$(function () {
|
||||
function LoginUiViewModel(parameters) {
|
||||
var self = this;
|
||||
self.loginState = parameters[0];
|
||||
self.access = parameters[1];
|
||||
self.coreWizardAcl = parameters[2];
|
||||
|
||||
self.onUserLoggedOut = self.onUserPermissionsChanged = function() {
|
||||
self.onUserLoggedOut = self.onUserPermissionsChanged = function () {
|
||||
// reload if user now lacks STATUS & SETTINGS_READ permissions and is not in first run setup, or is in
|
||||
// first run setup but the ACL wizard has already run and ACL is active
|
||||
if (!self.loginState.hasAllPermissions(self.access.permissions.STATUS, self.access.permissions.SETTINGS_READ)
|
||||
&& (!CONFIG_FIRST_RUN || (self.coreWizardAcl
|
||||
&& self.coreWizardAcl.setup()
|
||||
&& self.coreWizardAcl.decision()))) {
|
||||
if (
|
||||
!self.loginState.hasAllPermissions(
|
||||
self.access.permissions.STATUS,
|
||||
self.access.permissions.SETTINGS_READ
|
||||
) &&
|
||||
(!CONFIG_FIRST_RUN ||
|
||||
(self.coreWizardAcl &&
|
||||
self.coreWizardAcl.setup() &&
|
||||
self.coreWizardAcl.decision()))
|
||||
) {
|
||||
location.reload();
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: LoginUiViewModel,
|
||||
dependencies: ["loginStateViewModel", "accessViewModel", "coreWizardAclViewModel"],
|
||||
dependencies: [
|
||||
"loginStateViewModel",
|
||||
"accessViewModel",
|
||||
"coreWizardAclViewModel"
|
||||
],
|
||||
optional: ["coreWizardAclViewModel"]
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function NavigationViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -9,19 +9,25 @@ $(function() {
|
||||
self.system = parameters[4];
|
||||
self.access = parameters[5];
|
||||
|
||||
self.appearanceClasses = ko.pureComputed(function() {
|
||||
self.appearanceClasses = ko.pureComputed(function () {
|
||||
var classes = self.appearance.color();
|
||||
if (self.appearance.colorTransparent()) {
|
||||
classes += " transparent";
|
||||
}
|
||||
return classes;
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: NavigationViewModel,
|
||||
dependencies: ["loginStateViewModel", "appearanceViewModel", "settingsViewModel", "userSettingsViewModel", "systemViewModel", "accessViewModel"],
|
||||
dependencies: [
|
||||
"loginStateViewModel",
|
||||
"appearanceViewModel",
|
||||
"settingsViewModel",
|
||||
"userSettingsViewModel",
|
||||
"systemViewModel",
|
||||
"accessViewModel"
|
||||
],
|
||||
elements: ["#navbar"]
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
$(function() {
|
||||
var cleanProfile = function() {
|
||||
$(function () {
|
||||
var cleanProfile = function () {
|
||||
return {
|
||||
id: "",
|
||||
name: "",
|
||||
@@ -23,13 +23,11 @@ $(function() {
|
||||
},
|
||||
extruder: {
|
||||
count: 1,
|
||||
offsets: [
|
||||
[0,0]
|
||||
],
|
||||
offsets: [[0, 0]],
|
||||
nozzleDiameter: 0.4,
|
||||
sharedNozzle: false
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
function EditedProfileViewModel(profiles) {
|
||||
@@ -51,13 +49,20 @@ $(function() {
|
||||
self.volumeFormFactor = ko.observable();
|
||||
self.volumeOrigin = ko.observable();
|
||||
|
||||
self.volumeFormFactor.subscribe(function(value) {
|
||||
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.volumeOrigin.subscribe(function () {
|
||||
self.toBoundingBoxPlaceholders(
|
||||
self.defaultBoundingBox(
|
||||
self.volumeWidth(),
|
||||
self.volumeDepth(),
|
||||
self.volumeHeight(),
|
||||
self.volumeOrigin()
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
self.heatedBed = ko.observable();
|
||||
@@ -92,7 +97,7 @@ $(function() {
|
||||
self.boundingBoxMaxYPlaceholder = ko.observable();
|
||||
self.boundingBoxMaxZPlaceholder = ko.observable();
|
||||
|
||||
self.koExtruderOffsets = ko.pureComputed(function() {
|
||||
self.koExtruderOffsets = ko.pureComputed(function () {
|
||||
var extruderOffsets = self.extruderOffsets();
|
||||
var numExtruders = self.extruders();
|
||||
if (!numExtruders) {
|
||||
@@ -105,7 +110,7 @@ $(function() {
|
||||
idx: i + 1,
|
||||
x: ko.observable(0),
|
||||
y: ko.observable(0)
|
||||
}
|
||||
};
|
||||
}
|
||||
self.extruderOffsets(extruderOffsets);
|
||||
}
|
||||
@@ -113,11 +118,11 @@ $(function() {
|
||||
return extruderOffsets.slice(0, numExtruders - 1);
|
||||
});
|
||||
|
||||
self.nameInvalid = ko.pureComputed(function() {
|
||||
self.nameInvalid = ko.pureComputed(function () {
|
||||
return !self.name();
|
||||
});
|
||||
|
||||
self.identifierInvalid = ko.pureComputed(function() {
|
||||
self.identifierInvalid = ko.pureComputed(function () {
|
||||
var identifier = self.identifier();
|
||||
var placeholder = self.identifierPlaceholder();
|
||||
var data = identifier;
|
||||
@@ -125,13 +130,19 @@ $(function() {
|
||||
data = placeholder;
|
||||
}
|
||||
|
||||
var validCharacters = (data && (data == self._sanitize(data)));
|
||||
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);
|
||||
var existingProfile = self.profiles.getItem(function (item) {
|
||||
return item.id == data;
|
||||
});
|
||||
return (
|
||||
!data ||
|
||||
!validCharacters ||
|
||||
(self.isNew() && existingProfile != undefined)
|
||||
);
|
||||
});
|
||||
|
||||
self.identifierInvalidText = ko.pureComputed(function() {
|
||||
self.identifierInvalidText = ko.pureComputed(function () {
|
||||
if (!self.identifierInvalid()) {
|
||||
return "";
|
||||
}
|
||||
@@ -139,17 +150,19 @@ $(function() {
|
||||
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")
|
||||
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.name.subscribe(function () {
|
||||
self.identifierPlaceholder(self._sanitize(self.name()).toLowerCase());
|
||||
});
|
||||
|
||||
self.valid = function() {
|
||||
self.valid = function () {
|
||||
return !self.nameInvalid() && !self.identifierInvalid();
|
||||
};
|
||||
|
||||
@@ -163,12 +176,12 @@ $(function() {
|
||||
{key: "black", name: gettext("black")}
|
||||
]);
|
||||
|
||||
self.availableOrigins = ko.pureComputed(function() {
|
||||
self.availableOrigins = ko.pureComputed(function () {
|
||||
var formFactor = self.volumeFormFactor();
|
||||
|
||||
var possibleOrigins = {
|
||||
"lowerleft": gettext("Lower Left"),
|
||||
"center": gettext("Center")
|
||||
lowerleft: gettext("Lower Left"),
|
||||
center: gettext("Center")
|
||||
};
|
||||
|
||||
var keys = [];
|
||||
@@ -179,13 +192,13 @@ $(function() {
|
||||
}
|
||||
|
||||
var result = [];
|
||||
_.each(keys, function(key) {
|
||||
result.push({key: key, name: possibleOrigins[key]});
|
||||
_.each(keys, function (key) {
|
||||
result.push({key: key, name: possibleOrigins[key]});
|
||||
});
|
||||
return result;
|
||||
});
|
||||
|
||||
self.fromProfileData = function(data) {
|
||||
self.fromProfileData = function (data) {
|
||||
self.isNew(data === undefined);
|
||||
|
||||
if (data === undefined) {
|
||||
@@ -206,7 +219,12 @@ $(function() {
|
||||
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);
|
||||
var box = self.defaultBoundingBox(
|
||||
data.volume.width,
|
||||
data.volume.depth,
|
||||
data.volume.height,
|
||||
data.volume.origin
|
||||
);
|
||||
self.toBoundingBoxData(box, false);
|
||||
}
|
||||
|
||||
@@ -218,7 +236,7 @@ $(function() {
|
||||
self.extruders(data.extruder.count);
|
||||
var offsets = [];
|
||||
if (data.extruder.count > 1) {
|
||||
_.each(_.slice(data.extruder.offsets, 1), function(offset, index) {
|
||||
_.each(_.slice(data.extruder.offsets, 1), function (offset, index) {
|
||||
offsets.push({
|
||||
idx: index + 1,
|
||||
x: ko.observable(offset[0]),
|
||||
@@ -238,24 +256,24 @@ $(function() {
|
||||
self.axisEInverted(data.axes.e.inverted);
|
||||
};
|
||||
|
||||
self.toProfileData = function() {
|
||||
self.toProfileData = function () {
|
||||
var identifier = self.identifier();
|
||||
if (!identifier) {
|
||||
identifier = self.identifierPlaceholder();
|
||||
}
|
||||
|
||||
var defaultProfile = cleanProfile();
|
||||
var valid = function(value, f, def) {
|
||||
var valid = function (value, f, def) {
|
||||
var v = f(value);
|
||||
if (isNaN(v)) {
|
||||
return def;
|
||||
}
|
||||
return v;
|
||||
};
|
||||
var validFloat = function(value, def) {
|
||||
var validFloat = function (value, def) {
|
||||
return valid(value, parseFloat, def);
|
||||
};
|
||||
var validInt = function(value, def) {
|
||||
var validInt = function (value, def) {
|
||||
return valid(value, parseInt, def);
|
||||
};
|
||||
|
||||
@@ -275,10 +293,11 @@ $(function() {
|
||||
heatedChamber: self.heatedChamber(),
|
||||
extruder: {
|
||||
count: parseInt(self.extruders()),
|
||||
offsets: [
|
||||
[0.0, 0.0]
|
||||
],
|
||||
nozzleDiameter: validFloat(self.nozzleDiameter(), defaultProfile.extruder.nozzleDiameter),
|
||||
offsets: [[0.0, 0.0]],
|
||||
nozzleDiameter: validFloat(
|
||||
self.nozzleDiameter(),
|
||||
defaultProfile.extruder.nozzleDiameter
|
||||
),
|
||||
sharedNozzle: self.sharedNozzle()
|
||||
},
|
||||
axes: {
|
||||
@@ -323,7 +342,7 @@ $(function() {
|
||||
return profile;
|
||||
};
|
||||
|
||||
self.defaultBoundingBox = function(width, depth, height, origin) {
|
||||
self.defaultBoundingBox = function (width, depth, height, origin) {
|
||||
if (origin == "center") {
|
||||
var halfWidth = width / 2.0;
|
||||
var halfDepth = depth / 2.0;
|
||||
@@ -335,7 +354,7 @@ $(function() {
|
||||
x_max: halfWidth,
|
||||
y_max: halfDepth,
|
||||
z_max: height
|
||||
}
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
x_min: 0.0,
|
||||
@@ -344,11 +363,11 @@ $(function() {
|
||||
x_max: width,
|
||||
y_max: depth,
|
||||
z_max: height
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
self.toBoundingBoxData = function(box, custom) {
|
||||
self.toBoundingBoxData = function (box, custom) {
|
||||
self.customBoundingBox(custom);
|
||||
if (custom) {
|
||||
self.boundingBoxMinX(box.x_min);
|
||||
@@ -368,7 +387,7 @@ $(function() {
|
||||
self.toBoundingBoxPlaceholders(box);
|
||||
};
|
||||
|
||||
self.toBoundingBoxPlaceholders = function(box) {
|
||||
self.toBoundingBoxPlaceholders = function (box) {
|
||||
self.boundingBoxMinXPlaceholder(box.x_min);
|
||||
self.boundingBoxMinYPlaceholder(box.y_min);
|
||||
self.boundingBoxMinZPlaceholder(box.z_min);
|
||||
@@ -377,23 +396,46 @@ $(function() {
|
||||
self.boundingBoxMaxZPlaceholder(box.z_max);
|
||||
};
|
||||
|
||||
self.fillBoundingBoxData = function(profile) {
|
||||
self.fillBoundingBoxData = function (profile) {
|
||||
if (self.customBoundingBox()) {
|
||||
var defaultBox = self.defaultBoundingBox(self.volumeWidth(), self.volumeDepth(), self.volumeHeight(), self.volumeOrigin());
|
||||
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
|
||||
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) {
|
||||
self._sanitize = function (name) {
|
||||
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
|
||||
};
|
||||
|
||||
@@ -411,10 +453,12 @@ $(function() {
|
||||
self.profiles = new ItemListHelper(
|
||||
"printerProfiles",
|
||||
{
|
||||
"name": function(a, b) {
|
||||
name: function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase())
|
||||
return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase())
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
@@ -427,7 +471,7 @@ $(function() {
|
||||
self.defaultProfile = ko.observable();
|
||||
self.currentProfile = ko.observable();
|
||||
|
||||
self.createProfileEditor = function(data) {
|
||||
self.createProfileEditor = function (data) {
|
||||
var editor = new EditedProfileViewModel(self.profiles);
|
||||
if (data !== undefined) {
|
||||
editor.fromProfileData(data);
|
||||
@@ -438,11 +482,11 @@ $(function() {
|
||||
self.editor = self.createProfileEditor();
|
||||
self.currentProfileData = ko.observable(ko.mapping.fromJS(cleanProfile()));
|
||||
|
||||
self.enableEditorSubmitButton = ko.pureComputed(function() {
|
||||
self.enableEditorSubmitButton = ko.pureComputed(function () {
|
||||
return self.editor.valid() && !self.requestInProgress();
|
||||
});
|
||||
|
||||
self.makeDefault = function(data) {
|
||||
self.makeDefault = function (data) {
|
||||
var profile = {
|
||||
id: data.id,
|
||||
default: true
|
||||
@@ -451,35 +495,37 @@ $(function() {
|
||||
self.updateProfile(profile);
|
||||
};
|
||||
|
||||
self.canMakeDefault = function(data) {
|
||||
self.canMakeDefault = function (data) {
|
||||
return !data.isdefault();
|
||||
};
|
||||
|
||||
self.canRemove = function(data) {
|
||||
self.canRemove = function (data) {
|
||||
return !data.iscurrent() && !data.isdefault();
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
self.requestData = function () {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.CONNECTION)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return OctoPrint.printerprofiles.list()
|
||||
.done(self.fromResponse);
|
||||
return OctoPrint.printerprofiles.list().done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
self.fromResponse = function (data) {
|
||||
var items = [];
|
||||
var defaultProfile = undefined;
|
||||
var currentProfile = undefined;
|
||||
var currentProfileData = undefined;
|
||||
_.each(data.profiles, function(entry) {
|
||||
_.each(data.profiles, function (entry) {
|
||||
if (entry.default) {
|
||||
defaultProfile = entry.id;
|
||||
}
|
||||
if (entry.current) {
|
||||
currentProfile = entry.id;
|
||||
currentProfileData = ko.mapping.fromJS(entry, self.currentProfileData);
|
||||
currentProfileData = ko.mapping.fromJS(
|
||||
entry,
|
||||
self.currentProfileData
|
||||
);
|
||||
}
|
||||
entry["isdefault"] = ko.observable(entry.default);
|
||||
entry["iscurrent"] = ko.observable(entry.current);
|
||||
@@ -493,81 +539,114 @@ $(function() {
|
||||
self.currentProfileData(currentProfileData);
|
||||
} else {
|
||||
// shouldn't normally happen, but just to not have anything else crash...
|
||||
log.warn("Current printer profile could not be detected, using default values");
|
||||
log.warn(
|
||||
"Current printer profile could not be detected, using default values"
|
||||
);
|
||||
self.currentProfile("");
|
||||
self.currentProfileData(ko.mapping.fromJS(cleanProfile(), self.currentProfileData));
|
||||
self.currentProfileData(
|
||||
ko.mapping.fromJS(cleanProfile(), self.currentProfileData)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
self.addProfile = function(callback) {
|
||||
self.addProfile = function (callback) {
|
||||
var profile = self.editor.toProfileData();
|
||||
self.requestInProgress(true);
|
||||
OctoPrint.printerprofiles.add(profile)
|
||||
.done(function() {
|
||||
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});
|
||||
.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() {
|
||||
.always(function () {
|
||||
self.requestInProgress(false);
|
||||
});
|
||||
};
|
||||
|
||||
self.removeProfile = function(data) {
|
||||
var perform = function() {
|
||||
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);
|
||||
});
|
||||
OctoPrint.printerprofiles
|
||||
.delete(data.id, {url: data.resource})
|
||||
.done(function () {
|
||||
self.requestData().always(function () {
|
||||
self.requestInProgress(false);
|
||||
});
|
||||
})
|
||||
.fail(function(xhr) {
|
||||
.fail(function (xhr) {
|
||||
var text;
|
||||
if (xhr.status == 409) {
|
||||
text = gettext("Cannot delete the default profile or the currently active profile.");
|
||||
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.");
|
||||
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});
|
||||
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);
|
||||
showConfirmationDialog(
|
||||
_.sprintf(
|
||||
gettext('You are about to delete the printer profile "%(name)s".'),
|
||||
{name: _.escape(data.name)}
|
||||
),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.updateProfile = function(profile, callback) {
|
||||
self.updateProfile = function (profile, callback) {
|
||||
if (profile == undefined) {
|
||||
profile = self.editor.toProfileData();
|
||||
}
|
||||
|
||||
self.requestInProgress(true);
|
||||
OctoPrint.printerprofiles.update(profile.id, profile)
|
||||
.done(function() {
|
||||
OctoPrint.printerprofiles
|
||||
.update(profile.id, profile)
|
||||
.done(function () {
|
||||
if (callback !== undefined) {
|
||||
callback();
|
||||
}
|
||||
self.requestData()
|
||||
.always(function() {
|
||||
self.requestInProgress(false);
|
||||
});
|
||||
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});
|
||||
.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.showEditProfileDialog = function (data) {
|
||||
self.editor.fromProfileData(data);
|
||||
|
||||
var editDialog = $("#settings_printerProfiles_editDialog");
|
||||
@@ -575,25 +654,37 @@ $(function() {
|
||||
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)}));
|
||||
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() {
|
||||
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({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
editDialog
|
||||
.modal({
|
||||
minHeight: function () {
|
||||
return Math.max($.fn.modal.defaults.maxHeight() - 80, 250);
|
||||
}
|
||||
})
|
||||
.css({
|
||||
"width": "auto",
|
||||
"margin-left": function () {
|
||||
return -($(this).width() / 2);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.confirmEditProfile = function(add) {
|
||||
var callback = function() {
|
||||
self.confirmEditProfile = function (add) {
|
||||
var callback = function () {
|
||||
$("#settings_printerProfiles_editDialog").modal("hide");
|
||||
};
|
||||
|
||||
@@ -606,9 +697,9 @@ $(function() {
|
||||
|
||||
self.onSettingsShown = self.requestData;
|
||||
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function PrinterStateViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -18,32 +18,43 @@ $(function() {
|
||||
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.isBusy = ko.pureComputed(function () {
|
||||
return (
|
||||
self.isPrinting() ||
|
||||
self.isCancelling() ||
|
||||
self.isPausing() ||
|
||||
self.isPaused()
|
||||
);
|
||||
});
|
||||
|
||||
self.enablePrint = ko.pureComputed(function() {
|
||||
return self.isOperational() &&
|
||||
self.enablePrint = ko.pureComputed(function () {
|
||||
return (
|
||||
self.isOperational() &&
|
||||
self.isReady() &&
|
||||
!self.isPrinting() &&
|
||||
!self.isCancelling() &&
|
||||
!self.isPausing() &&
|
||||
self.loginState.hasPermission(self.access.permissions.PRINT) &&
|
||||
self.filename();
|
||||
self.filename()
|
||||
);
|
||||
});
|
||||
self.enablePause = ko.pureComputed(function() {
|
||||
return self.isOperational() &&
|
||||
self.enablePause = ko.pureComputed(function () {
|
||||
return (
|
||||
self.isOperational() &&
|
||||
(self.isPrinting() || self.isPaused()) &&
|
||||
!self.isCancelling() &&
|
||||
!self.isPausing() &&
|
||||
self.loginState.hasPermission(self.access.permissions.PRINT);
|
||||
self.loginState.hasPermission(self.access.permissions.PRINT)
|
||||
);
|
||||
});
|
||||
self.enableCancel = ko.pureComputed(function() {
|
||||
return self.isOperational() &&
|
||||
self.enableCancel = ko.pureComputed(function () {
|
||||
return (
|
||||
self.isOperational() &&
|
||||
(self.isPrinting() || self.isPaused()) &&
|
||||
!self.isCancelling() &&
|
||||
!self.isPausing() &&
|
||||
self.loginState.loggedIn();
|
||||
self.loginState.loggedIn()
|
||||
);
|
||||
});
|
||||
|
||||
self.filename = ko.observable(undefined);
|
||||
@@ -68,7 +79,9 @@ $(function() {
|
||||
|
||||
self.currentHeight = ko.observable(undefined);
|
||||
|
||||
self.TITLE_PRINT_BUTTON_PAUSED = gettext("Restarts the print job from the beginning");
|
||||
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");
|
||||
@@ -77,32 +90,31 @@ $(function() {
|
||||
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());
|
||||
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.estimatedPrintTimeString = ko.pureComputed(function () {
|
||||
return estimatedPrintTimeStringHlpr(
|
||||
self.settings.appearance_fuzzyTimes()
|
||||
? formatFuzzyPrintTime
|
||||
: formatDuration
|
||||
);
|
||||
});
|
||||
self.estimatedPrintTimeExactString = ko.pureComputed(function() {
|
||||
self.estimatedPrintTimeExactString = ko.pureComputed(function () {
|
||||
return estimatedPrintTimeStringHlpr(formatDuration);
|
||||
});
|
||||
self.byteString = ko.pureComputed(function() {
|
||||
if (!self.filesize())
|
||||
return "-";
|
||||
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 "-";
|
||||
self.heightString = ko.pureComputed(function () {
|
||||
if (!self.currentHeight()) return "-";
|
||||
return _.sprintf("%.02fmm", self.currentHeight());
|
||||
});
|
||||
self.printTimeString = ko.pureComputed(function() {
|
||||
if (!self.printTime())
|
||||
return "-";
|
||||
self.printTimeString = ko.pureComputed(function () {
|
||||
if (!self.printTime()) return "-";
|
||||
return formatDuration(self.printTime());
|
||||
});
|
||||
var printTimeLeftStringHlpr = function (fmt) {
|
||||
@@ -116,29 +128,43 @@ $(function() {
|
||||
return fmt(self.printTimeLeft());
|
||||
}
|
||||
};
|
||||
self.printTimeLeftString = ko.pureComputed(function() {
|
||||
return printTimeLeftStringHlpr(self.settings.appearance_fuzzyTimes() ? formatFuzzyPrintTime : formatDuration);
|
||||
self.printTimeLeftString = ko.pureComputed(function () {
|
||||
return printTimeLeftStringHlpr(
|
||||
self.settings.appearance_fuzzyTimes()
|
||||
? formatFuzzyPrintTime
|
||||
: formatDuration
|
||||
);
|
||||
});
|
||||
self.printTimeLeftExactString = ko.pureComputed(function() {
|
||||
self.printTimeLeftExactString = ko.pureComputed(function () {
|
||||
return printTimeLeftStringHlpr(formatDuration);
|
||||
});
|
||||
self.printTimeLeftOriginString = ko.pureComputed(function() {
|
||||
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)");
|
||||
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)");
|
||||
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)");
|
||||
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)");
|
||||
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)");
|
||||
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)");
|
||||
@@ -148,7 +174,7 @@ $(function() {
|
||||
}
|
||||
}
|
||||
});
|
||||
self.printTimeLeftOriginClass = ko.pureComputed(function() {
|
||||
self.printTimeLeftOriginClass = ko.pureComputed(function () {
|
||||
var value = self.printTimeLeftOrigin();
|
||||
switch (value) {
|
||||
default:
|
||||
@@ -166,41 +192,44 @@ $(function() {
|
||||
}
|
||||
}
|
||||
});
|
||||
self.progressString = ko.pureComputed(function() {
|
||||
if (!self.progress())
|
||||
return 0;
|
||||
self.progressString = ko.pureComputed(function () {
|
||||
if (!self.progress()) return 0;
|
||||
return self.progress();
|
||||
});
|
||||
self.progressBarString = ko.pureComputed(function() {
|
||||
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.pauseString = ko.pureComputed(function () {
|
||||
if (self.isPaused()) return gettext("Continue");
|
||||
else return gettext("Pause");
|
||||
});
|
||||
|
||||
self.timelapseString = ko.pureComputed(function() {
|
||||
self.timelapseString = ko.pureComputed(function () {
|
||||
var timelapse = self.timelapse();
|
||||
|
||||
if (!timelapse || !timelapse.hasOwnProperty("type"))
|
||||
return "-";
|
||||
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") + ")";
|
||||
return (
|
||||
gettext("Timed") +
|
||||
" (" +
|
||||
timelapse["options"]["interval"] +
|
||||
" " +
|
||||
gettext("sec") +
|
||||
")"
|
||||
);
|
||||
} else {
|
||||
return "-";
|
||||
}
|
||||
});
|
||||
|
||||
self.userString = ko.pureComputed(function() {
|
||||
self.userString = ko.pureComputed(function () {
|
||||
var user = self.user();
|
||||
if (!CONFIG_ACCESS_CONTROL || user === "_dummy") {
|
||||
return "";
|
||||
@@ -211,31 +240,31 @@ $(function() {
|
||||
}
|
||||
|
||||
var file = self.filename();
|
||||
return (user ? user : (file ? "-" : ""));
|
||||
return user ? user : file ? "-" : "";
|
||||
});
|
||||
|
||||
self.dateString = ko.pureComputed(function() {
|
||||
self.dateString = ko.pureComputed(function () {
|
||||
var date = self.filedate();
|
||||
if (!date) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return formatDate(date, {seconds:true});
|
||||
return formatDate(date, {seconds: true});
|
||||
});
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self.fromCurrentData = function (data) {
|
||||
self._fromData(data);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self.fromHistoryData = function (data) {
|
||||
self._fromData(data);
|
||||
};
|
||||
|
||||
self.fromTimelapseData = function(data) {
|
||||
self.fromTimelapseData = function (data) {
|
||||
self.timelapse(data);
|
||||
};
|
||||
|
||||
self._fromData = function(data) {
|
||||
self._fromData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
self._processJobData(data.job);
|
||||
self._processProgressData(data.progress);
|
||||
@@ -243,7 +272,7 @@ $(function() {
|
||||
self._processBusyFiles(data.busyFiles);
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self._processStateData = function (data) {
|
||||
var prevPaused = self.isPaused();
|
||||
|
||||
self.stateString(gettext(data.text));
|
||||
@@ -268,7 +297,7 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._processJobData = function(data) {
|
||||
self._processJobData = function (data) {
|
||||
if (data.file) {
|
||||
self.filename(data.file.name);
|
||||
self.filepath(data.file.path);
|
||||
@@ -289,14 +318,26 @@ $(function() {
|
||||
self.lastPrintTime(data.lastPrintTime);
|
||||
|
||||
var result = [];
|
||||
if (data.filament && typeof(data.filament) === "object" && _.keys(data.filament).length > 0) {
|
||||
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;
|
||||
_.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)),
|
||||
name: ko.observable(
|
||||
gettext("Tool") + " " + key.substr("tool".length)
|
||||
),
|
||||
data: ko.observable(data.filament[key])
|
||||
});
|
||||
});
|
||||
@@ -306,7 +347,7 @@ $(function() {
|
||||
self.user(data.user);
|
||||
};
|
||||
|
||||
self._processProgressData = function(data) {
|
||||
self._processProgressData = function (data) {
|
||||
if (data.completion) {
|
||||
self.progress(data.completion);
|
||||
} else {
|
||||
@@ -318,13 +359,13 @@ $(function() {
|
||||
self.printTimeLeftOrigin(data.printTimeLeftOrigin);
|
||||
};
|
||||
|
||||
self._processZData = function(data) {
|
||||
self._processZData = function (data) {
|
||||
self.currentHeight(data);
|
||||
};
|
||||
|
||||
self._processBusyFiles = function(data) {
|
||||
self._processBusyFiles = function (data) {
|
||||
var busyFiles = [];
|
||||
_.each(data, function(entry) {
|
||||
_.each(data, function (entry) {
|
||||
if (entry.hasOwnProperty("path") && entry.hasOwnProperty("origin")) {
|
||||
busyFiles.push(entry.origin + ":" + entry.path);
|
||||
}
|
||||
@@ -332,11 +373,13 @@ $(function() {
|
||||
self.busyFiles(busyFiles);
|
||||
};
|
||||
|
||||
self.print = function() {
|
||||
self.print = function () {
|
||||
if (self.isPaused()) {
|
||||
showConfirmationDialog({
|
||||
message: gettext("This will restart the print job from the beginning."),
|
||||
onproceed: function() {
|
||||
message: gettext(
|
||||
"This will restart the print job from the beginning."
|
||||
),
|
||||
onproceed: function () {
|
||||
OctoPrint.job.restart();
|
||||
}
|
||||
});
|
||||
@@ -345,33 +388,34 @@ $(function() {
|
||||
OctoPrint.job.start();
|
||||
} else {
|
||||
showConfirmationDialog({
|
||||
message: gettext("This will start a new print job. Please check that the print bed is clear."),
|
||||
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() {
|
||||
onproceed: function () {
|
||||
OctoPrint.job.start();
|
||||
},
|
||||
nofade: true
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
self.onlyPause = function() {
|
||||
self.onlyPause = function () {
|
||||
OctoPrint.job.pause();
|
||||
};
|
||||
|
||||
self.onlyResume = function() {
|
||||
self.onlyResume = function () {
|
||||
OctoPrint.job.resume();
|
||||
};
|
||||
|
||||
self.pause = function(action) {
|
||||
self.pause = function (action) {
|
||||
OctoPrint.job.togglePause();
|
||||
};
|
||||
|
||||
self.cancel = function() {
|
||||
self.cancel = function () {
|
||||
if (!self.settings.feature_printCancelConfirmation()) {
|
||||
OctoPrint.job.cancel();
|
||||
} else {
|
||||
@@ -379,7 +423,7 @@ $(function() {
|
||||
message: gettext("This will cancel your print."),
|
||||
cancel: gettext("No, continue the print"),
|
||||
proceed: gettext("Yes, cancel the print"),
|
||||
onproceed: function() {
|
||||
onproceed: function () {
|
||||
OctoPrint.job.cancel();
|
||||
},
|
||||
nofade: true
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function SlicingViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -29,19 +29,19 @@ $(function() {
|
||||
|
||||
self.allViewModels = undefined;
|
||||
|
||||
self.slicersForFile = function(file) {
|
||||
self.slicersForFile = function (file) {
|
||||
if (file === undefined) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return _.filter(self.configuredSlicers(), function(slicer) {
|
||||
return _.any(slicer.sourceExtensions, function(extension) {
|
||||
return _.filter(self.configuredSlicers(), function (slicer) {
|
||||
return _.any(slicer.sourceExtensions, function (extension) {
|
||||
return _.endsWith(file.toLowerCase(), "." + extension.toLowerCase());
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
self.profilesForSlicer = function(key) {
|
||||
self.profilesForSlicer = function (key) {
|
||||
if (key == undefined) {
|
||||
key = self.slicer();
|
||||
}
|
||||
@@ -52,7 +52,7 @@ $(function() {
|
||||
|
||||
var selectedProfile = undefined;
|
||||
self.profiles.removeAll();
|
||||
_.each(_.values(slicer.profiles), function(profile) {
|
||||
_.each(_.values(slicer.profiles), function (profile) {
|
||||
var name = profile.displayName;
|
||||
if (name == undefined) {
|
||||
name = profile.key;
|
||||
@@ -65,19 +65,19 @@ $(function() {
|
||||
self.profiles.push({
|
||||
key: profile.key,
|
||||
name: name
|
||||
})
|
||||
});
|
||||
});
|
||||
|
||||
self.profile(selectedProfile);
|
||||
self.defaultProfile = selectedProfile;
|
||||
};
|
||||
|
||||
self.resetProfiles = function() {
|
||||
self.resetProfiles = function () {
|
||||
self.profiles.removeAll();
|
||||
self.profile(undefined);
|
||||
};
|
||||
|
||||
self.metadataForSlicer = function(key) {
|
||||
self.metadataForSlicer = function (key) {
|
||||
if (key == undefined || !self.data.hasOwnProperty(key)) {
|
||||
return;
|
||||
}
|
||||
@@ -86,28 +86,31 @@ $(function() {
|
||||
self.slicerSameDevice(slicer.sameDevice);
|
||||
};
|
||||
|
||||
self.resetMetadata = function() {
|
||||
self.resetMetadata = function () {
|
||||
self.slicerSameDevice(true);
|
||||
};
|
||||
|
||||
self.configuredSlicers = ko.pureComputed(function() {
|
||||
return _.filter(self.slicers(), function(slicer) {
|
||||
self.configuredSlicers = ko.pureComputed(function () {
|
||||
return _.filter(self.slicers(), function (slicer) {
|
||||
return slicer.configured;
|
||||
});
|
||||
});
|
||||
|
||||
self.matchingSlicers = ko.computed(function() {
|
||||
self.matchingSlicers = ko.computed(function () {
|
||||
var slicers = self.slicersForFile(self.file());
|
||||
|
||||
var containsSlicer = function(key) {
|
||||
return _.any(slicers, function(slicer) {
|
||||
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)) {
|
||||
if (
|
||||
self.defaultSlicer !== undefined &&
|
||||
containsSlicer(self.defaultSlicer)
|
||||
) {
|
||||
self.slicer(self.defaultSlicer);
|
||||
} else {
|
||||
self.slicer(undefined);
|
||||
@@ -121,13 +124,13 @@ $(function() {
|
||||
});
|
||||
|
||||
self.afterSlicingOptions = [
|
||||
{"value": "none", "text": gettext("Do nothing")},
|
||||
{"value": "select", "text": gettext("Select for printing")},
|
||||
{"value": "print", "text": gettext("Start printing")}
|
||||
{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) {
|
||||
self.show = function (target, file, force, path, options) {
|
||||
options = options || {};
|
||||
|
||||
if (!self.enableSlicingDialog() && !force) {
|
||||
@@ -147,7 +150,9 @@ $(function() {
|
||||
self.target = target;
|
||||
self.file(file);
|
||||
self.path = path;
|
||||
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: _.escape(display)}));
|
||||
self.title(
|
||||
_.sprintf(gettext("Slicing %(filename)s"), {filename: _.escape(display)})
|
||||
);
|
||||
self.destinationFilename(destination);
|
||||
self.printerProfile(self.printerProfiles.currentProfile());
|
||||
self.afterSlicing("none");
|
||||
@@ -155,7 +160,7 @@ $(function() {
|
||||
$("#slicing_configuration_dialog").modal("show");
|
||||
};
|
||||
|
||||
self.slicer.subscribe(function(newValue) {
|
||||
self.slicer.subscribe(function (newValue) {
|
||||
if (newValue === undefined) {
|
||||
self.resetProfiles();
|
||||
self.resetMetadata();
|
||||
@@ -165,25 +170,31 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
self.enableSlicingDialog = ko.pureComputed(function() {
|
||||
self.enableSlicingDialog = ko.pureComputed(function () {
|
||||
return self.configuredSlicers().length > 0;
|
||||
});
|
||||
|
||||
self.enableSlicingDialogForFile = function(file) {
|
||||
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.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() {
|
||||
self.sliceButtonTooltip = ko.pureComputed(function () {
|
||||
if (!self.enableSliceButton()) {
|
||||
if ((self.printerState.isPrinting() || self.printerState.isPaused()) && self.slicerSameDevice()) {
|
||||
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");
|
||||
@@ -193,18 +204,17 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
self.requestData = function() {
|
||||
self.requestData = function () {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.SLICE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return OctoPrint.slicing.listAllSlicersAndProfiles()
|
||||
.done(function(data) {
|
||||
self.fromResponse(data);
|
||||
});
|
||||
return OctoPrint.slicing.listAllSlicersAndProfiles().done(function (data) {
|
||||
self.fromResponse(data);
|
||||
});
|
||||
};
|
||||
|
||||
self.destinationExtension = ko.pureComputed(function() {
|
||||
self.destinationExtension = ko.pureComputed(function () {
|
||||
var fallback = "???";
|
||||
if (self.slicer() === undefined) {
|
||||
return fallback;
|
||||
@@ -225,12 +235,12 @@ $(function() {
|
||||
return destinationExtensions[0] || fallback;
|
||||
});
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
self.fromResponse = function (data) {
|
||||
self.data = data;
|
||||
|
||||
var selectedSlicer = undefined;
|
||||
self.slicers.removeAll();
|
||||
_.each(_.values(data), function(slicer) {
|
||||
_.each(_.values(data), function (slicer) {
|
||||
var name = slicer.displayName;
|
||||
if (name == undefined) {
|
||||
name = slicer.key;
|
||||
@@ -258,20 +268,29 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.slice = function() {
|
||||
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 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 = {
|
||||
@@ -291,36 +310,40 @@ $(function() {
|
||||
data["select"] = true;
|
||||
}
|
||||
|
||||
OctoPrint.files.slice(self.target, self.file(), data)
|
||||
.done(function() {
|
||||
$("#slicing_configuration_dialog").modal("hide");
|
||||
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.destinationFilename(undefined);
|
||||
self.slicer(self.defaultSlicer);
|
||||
self.profile(self.defaultProfile);
|
||||
});
|
||||
};
|
||||
|
||||
self._sanitize = function(name) {
|
||||
self._sanitize = function (name) {
|
||||
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
|
||||
};
|
||||
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventSettingsUpdated = function(payload) {
|
||||
self.onEventSettingsUpdated = function (payload) {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onAllBound = function(allViewModels) {
|
||||
self.onAllBound = function (allViewModels) {
|
||||
self.allViewModels = allViewModels;
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
construct: SlicingViewModel,
|
||||
dependencies: ["loginStateViewModel", "printerProfilesViewModel", "printerStateViewModel", "accessViewModel"],
|
||||
dependencies: [
|
||||
"loginStateViewModel",
|
||||
"printerProfilesViewModel",
|
||||
"printerStateViewModel",
|
||||
"accessViewModel"
|
||||
],
|
||||
elements: ["#slicing_configuration_dialog"]
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function SystemViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -8,23 +8,22 @@ $(function() {
|
||||
self.lastCommandResponse = undefined;
|
||||
self.systemActions = ko.observableArray([]);
|
||||
|
||||
self.requestData = function() {
|
||||
self.requestData = function () {
|
||||
self.requestCommandData();
|
||||
};
|
||||
|
||||
self.requestCommandData = function() {
|
||||
self.requestCommandData = function () {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
|
||||
return $.Deferred().reject().promise();
|
||||
}
|
||||
|
||||
return OctoPrint.system.getCommands()
|
||||
.done(self.fromCommandResponse);
|
||||
return OctoPrint.system.getCommands().done(self.fromCommandResponse);
|
||||
};
|
||||
|
||||
self.fromCommandResponse = function(response) {
|
||||
self.fromCommandResponse = function (response) {
|
||||
var actions = [];
|
||||
if (response.core && response.core.length) {
|
||||
_.each(response.core, function(data) {
|
||||
_.each(response.core, function (data) {
|
||||
var action = _.extend({}, data);
|
||||
action.actionSource = "core";
|
||||
actions.push(action);
|
||||
@@ -33,7 +32,7 @@ $(function() {
|
||||
actions.push({action: "divider"});
|
||||
}
|
||||
}
|
||||
_.each(response.custom, function(data) {
|
||||
_.each(response.custom, function (data) {
|
||||
var action = _.extend({}, data);
|
||||
action.actionSource = "custom";
|
||||
actions.push(action);
|
||||
@@ -42,21 +41,26 @@ $(function() {
|
||||
self.systemActions(actions);
|
||||
};
|
||||
|
||||
self.triggerCommand = function(commandSpec) {
|
||||
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 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");
|
||||
text = gettext(
|
||||
'The command "%(command)s" was triggered asynchronously'
|
||||
);
|
||||
} else {
|
||||
text = gettext("The command \"%(command)s\" executed successfully");
|
||||
text = gettext(
|
||||
'The command "%(command)s" executed successfully'
|
||||
);
|
||||
}
|
||||
|
||||
new PNotify({
|
||||
@@ -66,11 +70,29 @@ $(function() {
|
||||
});
|
||||
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});
|
||||
.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]);
|
||||
@@ -81,10 +103,10 @@ $(function() {
|
||||
if (commandSpec.confirm) {
|
||||
showConfirmationDialog({
|
||||
message: commandSpec.confirm,
|
||||
onproceed: function() {
|
||||
onproceed: function () {
|
||||
callback();
|
||||
},
|
||||
oncancel: function() {
|
||||
oncancel: function () {
|
||||
deferred.reject("cancelled", arguments);
|
||||
}
|
||||
});
|
||||
@@ -95,7 +117,9 @@ $(function() {
|
||||
return deferred.promise();
|
||||
};
|
||||
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function(user) {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function (
|
||||
user
|
||||
) {
|
||||
if (self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
|
||||
self.requestData();
|
||||
} else {
|
||||
@@ -104,7 +128,7 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.onEventSettingsUpdated = function() {
|
||||
self.onEventSettingsUpdated = function () {
|
||||
if (self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
|
||||
self.requestData();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function TemperatureViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -6,7 +6,7 @@ $(function() {
|
||||
self.settingsViewModel = parameters[1];
|
||||
self.access = parameters[2];
|
||||
|
||||
self._createToolEntry = function() {
|
||||
self._createToolEntry = function () {
|
||||
var entry = {
|
||||
name: ko.observable(),
|
||||
key: ko.observable(),
|
||||
@@ -17,7 +17,7 @@ $(function() {
|
||||
newOffset: ko.observable()
|
||||
};
|
||||
|
||||
entry.newTargetValid = ko.pureComputed(function() {
|
||||
entry.newTargetValid = ko.pureComputed(function () {
|
||||
var value = entry.newTarget();
|
||||
|
||||
try {
|
||||
@@ -26,10 +26,10 @@ $(function() {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (value >= 0 && value <= 999);
|
||||
return value >= 0 && value <= 999;
|
||||
});
|
||||
|
||||
entry.newOffsetValid = ko.pureComputed(function() {
|
||||
entry.newOffsetValid = ko.pureComputed(function () {
|
||||
var value = entry.newOffset();
|
||||
|
||||
try {
|
||||
@@ -38,11 +38,14 @@ $(function() {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (-50 <= value <= 50);
|
||||
return -50 <= value <= 50;
|
||||
});
|
||||
|
||||
entry.offset.subscribe(function(newValue) {
|
||||
if (self.changingOffset.item !== undefined && self.changingOffset.item.key() === entry.key()) {
|
||||
entry.offset.subscribe(function (newValue) {
|
||||
if (
|
||||
self.changingOffset.item !== undefined &&
|
||||
self.changingOffset.item.key() === entry.key()
|
||||
) {
|
||||
// if our we currently have the offset dialog open for this entry and the offset changed
|
||||
// meanwhile, update the displayed value in the dialog
|
||||
self.changingOffset.offset(newValue);
|
||||
@@ -58,12 +61,18 @@ $(function() {
|
||||
name: ko.observable(""),
|
||||
item: undefined,
|
||||
|
||||
title: ko.pureComputed(function() {
|
||||
return _.sprintf(gettext("Changing Offset of %(name)s"), {name: _.escape(self.changingOffset.name())});
|
||||
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())});
|
||||
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;
|
||||
@@ -72,13 +81,13 @@ $(function() {
|
||||
self.loginStateSubscription = undefined;
|
||||
|
||||
self.tools = ko.observableArray([]);
|
||||
self.hasTools = ko.pureComputed(function() {
|
||||
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() {
|
||||
self.visible = ko.pureComputed(function () {
|
||||
return self.hasTools() || self.hasBed();
|
||||
});
|
||||
|
||||
@@ -107,7 +116,7 @@ $(function() {
|
||||
self._currentTemperatureDataBacklog = [];
|
||||
self._historyTemperatureDataBacklog = [];
|
||||
|
||||
self._printerProfileUpdated = function() {
|
||||
self._printerProfileUpdated = function () {
|
||||
var graphColors = ["red", "orange", "green", "brown", "purple"];
|
||||
var heaterOptions = {};
|
||||
var tools = [];
|
||||
@@ -115,14 +124,21 @@ $(function() {
|
||||
|
||||
// tools
|
||||
var currentProfileData = self.settingsViewModel.printerProfiles.currentProfileData();
|
||||
var numExtruders = (currentProfileData ? currentProfileData.extruder.count() : 0);
|
||||
var sharedNozzle = (currentProfileData ? currentProfileData.extruder.sharedNozzle() : false);
|
||||
var numExtruders = currentProfileData
|
||||
? currentProfileData.extruder.count()
|
||||
: 0;
|
||||
var sharedNozzle = currentProfileData
|
||||
? currentProfileData.extruder.sharedNozzle()
|
||||
: false;
|
||||
if (numExtruders && numExtruders > 1 && !sharedNozzle) {
|
||||
// multiple extruders
|
||||
for (var extruder = 0; extruder < numExtruders; extruder++) {
|
||||
color = graphColors.shift();
|
||||
if (!color) color = "black";
|
||||
heaterOptions["tool" + extruder] = {name: "T" + extruder, color: color};
|
||||
heaterOptions["tool" + extruder] = {
|
||||
name: "T" + extruder,
|
||||
color: color
|
||||
};
|
||||
|
||||
if (tools.length <= extruder || !tools[extruder]) {
|
||||
tools[extruder] = self._createToolEntry();
|
||||
@@ -168,12 +184,20 @@ $(function() {
|
||||
self.updatePlot();
|
||||
};
|
||||
|
||||
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
|
||||
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.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.temperatures = [];
|
||||
@@ -182,7 +206,7 @@ $(function() {
|
||||
self.plotHoverPos = undefined;
|
||||
self.plotLegendTimeout = undefined;
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self.fromCurrentData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
if (!self._printerProfileInitialized) {
|
||||
self._currentTemperatureDataBacklog.push(data);
|
||||
@@ -192,7 +216,7 @@ $(function() {
|
||||
self._processOffsetData(data.offsets);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self.fromHistoryData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
if (!self._printerProfileInitialized) {
|
||||
self._historyTemperatureDataBacklog.push(data);
|
||||
@@ -202,11 +226,11 @@ $(function() {
|
||||
self._processOffsetData(data.offsets);
|
||||
};
|
||||
|
||||
self._triggerBacklog = function() {
|
||||
_.each(self._historyTemperatureDataBacklog, function(data) {
|
||||
self._triggerBacklog = function () {
|
||||
_.each(self._historyTemperatureDataBacklog, function (data) {
|
||||
self._processTemperatureHistoryData(data.serverTime, data.temps);
|
||||
});
|
||||
_.each(self._currentTemperatureDataBacklog, function(data) {
|
||||
_.each(self._currentTemperatureDataBacklog, function (data) {
|
||||
self._processTemperatureUpdateData(data.serverTime, data.temps);
|
||||
});
|
||||
self._historyTemperatureDataBacklog = [];
|
||||
@@ -214,7 +238,7 @@ $(function() {
|
||||
self._printerProfileInitialized = true;
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self._processStateData = function (data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
@@ -224,9 +248,8 @@ $(function() {
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
self._processTemperatureUpdateData = function(serverTime, data) {
|
||||
if (data.length === 0)
|
||||
return;
|
||||
self._processTemperatureUpdateData = function (serverTime, data) {
|
||||
if (data.length === 0) return;
|
||||
|
||||
var lastData = data[data.length - 1];
|
||||
|
||||
@@ -259,16 +282,20 @@ $(function() {
|
||||
|
||||
if (!CONFIG_TEMPERATURE_GRAPH) return;
|
||||
|
||||
self.temperatures = self._processTemperatureData(serverTime, data, self.temperatures);
|
||||
self.temperatures = self._processTemperatureData(
|
||||
serverTime,
|
||||
data,
|
||||
self.temperatures
|
||||
);
|
||||
self.updatePlot();
|
||||
};
|
||||
|
||||
self._processTemperatureHistoryData = function(serverTime, data) {
|
||||
self._processTemperatureHistoryData = function (serverTime, data) {
|
||||
self.temperatures = self._processTemperatureData(serverTime, data);
|
||||
self.updatePlot();
|
||||
};
|
||||
|
||||
self._processOffsetData = function(data) {
|
||||
self._processOffsetData = function (data) {
|
||||
var tools = self.tools();
|
||||
for (var i = 0; i < tools.length; i++) {
|
||||
if (data.hasOwnProperty("tool" + i)) {
|
||||
@@ -291,7 +318,7 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._processTemperatureData = function(serverTime, data, result) {
|
||||
self._processTemperatureData = function (serverTime, data, result) {
|
||||
var types = _.keys(self.heaterOptions());
|
||||
var clientTime = Date.now();
|
||||
|
||||
@@ -300,7 +327,7 @@ $(function() {
|
||||
result = {};
|
||||
}
|
||||
|
||||
_.each(types, function(type) {
|
||||
_.each(types, function (type) {
|
||||
if (!result.hasOwnProperty(type)) {
|
||||
result[type] = {actual: [], target: []};
|
||||
}
|
||||
@@ -309,23 +336,23 @@ $(function() {
|
||||
});
|
||||
|
||||
// convert data
|
||||
_.each(data, function(d) {
|
||||
_.each(data, function (d) {
|
||||
var timeDiff = (serverTime - d.time) * 1000;
|
||||
var time = clientTime - timeDiff;
|
||||
_.each(types, function(type) {
|
||||
_.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) {
|
||||
var filterOld = function(item) {
|
||||
var filterOld = function (item) {
|
||||
return item[0] >= clientTime - temperature_cutoff * 60 * 1000;
|
||||
};
|
||||
|
||||
_.each(_.keys(self.heaterOptions()), function(d) {
|
||||
_.each(_.keys(self.heaterOptions()), function (d) {
|
||||
result[d].actual = _.filter(result[d].actual, filterOld);
|
||||
result[d].target = _.filter(result[d].target, filterOld);
|
||||
});
|
||||
@@ -334,10 +361,10 @@ $(function() {
|
||||
return result;
|
||||
};
|
||||
|
||||
self.profileText = function(heater, profile) {
|
||||
self.profileText = function (heater, profile) {
|
||||
var text = gettext("Set %(name)s (%(value)s)");
|
||||
|
||||
var format = function(temp) {
|
||||
var format = function (temp) {
|
||||
if (temp === 0 || temp === undefined || temp === null) {
|
||||
return gettext("Off");
|
||||
} else {
|
||||
@@ -354,7 +381,11 @@ $(function() {
|
||||
if (self.hasChamber()) {
|
||||
value += "/" + gettext("Chamber") + ": %(chamber)s";
|
||||
}
|
||||
value = _.sprintf(value, {extruder: format(profile.extruder), bed: format(profile.bed), chamber: format(profile.chamber)});
|
||||
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") {
|
||||
@@ -363,10 +394,13 @@ $(function() {
|
||||
value = format(profile.extruder);
|
||||
}
|
||||
|
||||
return _.sprintf(text, {name: _.escape(profile.name), value: _.escape(value)});
|
||||
return _.sprintf(text, {
|
||||
name: _.escape(profile.name),
|
||||
value: _.escape(value)
|
||||
});
|
||||
};
|
||||
|
||||
self.updatePlot = function() {
|
||||
self.updatePlot = function () {
|
||||
var graph = $("#temperature-graph");
|
||||
if (!graph.length) return; // no graph
|
||||
if (!self.plot) return; // plot not yet initialized
|
||||
@@ -387,7 +421,7 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._initializePlot = function(force, plotInfo) {
|
||||
self._initializePlot = function (force, plotInfo) {
|
||||
var graph = $("#temperature-graph");
|
||||
if (!graph.length) return; // no graph
|
||||
if (self.plot && !force) return; // already initialized
|
||||
@@ -401,18 +435,16 @@ $(function() {
|
||||
min: 0,
|
||||
max: Math.max(Math.max.apply(null, plotInfo.max) * 1.1, 310),
|
||||
ticks: 10,
|
||||
tickFormatter: function(val, axis) {
|
||||
if (val === undefined || val === 0)
|
||||
return "";
|
||||
tickFormatter: function (val, axis) {
|
||||
if (val === undefined || val === 0) return "";
|
||||
return val + "°C";
|
||||
}
|
||||
},
|
||||
xaxis: {
|
||||
mode: "time",
|
||||
minTickSize: [2, "minute"],
|
||||
tickFormatter: function(val, axis) {
|
||||
if (val === undefined || val === 0)
|
||||
return ""; // we don't want to display the minutes since the epoch if not connected yet ;)
|
||||
tickFormatter: function (val, axis) {
|
||||
if (val === undefined || val === 0) return ""; // we don't want to display the minutes since the epoch if not connected yet ;)
|
||||
|
||||
// current time in milliseconds in UTC
|
||||
var timestampUtc = Date.now();
|
||||
@@ -441,24 +473,24 @@ $(function() {
|
||||
};
|
||||
|
||||
if (!OctoPrint.coreui.browser.mobile) {
|
||||
options["crosshair"] = { mode: "x" };
|
||||
options["grid"] = { hoverable: true, autoHighlight: false };
|
||||
options["crosshair"] = {mode: "x"};
|
||||
options["grid"] = {hoverable: true, autoHighlight: false};
|
||||
}
|
||||
|
||||
self.plot = $.plot(graph, plotInfo.data, options);
|
||||
};
|
||||
|
||||
self._getPlotInfo = function() {
|
||||
self._getPlotInfo = function () {
|
||||
var data = [];
|
||||
var heaterOptions = self.heaterOptions();
|
||||
if (!heaterOptions) return undefined;
|
||||
|
||||
var maxTemps = [310/1.1];
|
||||
var maxTemps = [310 / 1.1];
|
||||
var now = Date.now();
|
||||
|
||||
var showFahrenheit = self._shallShowFahrenheit();
|
||||
|
||||
_.each(_.keys(heaterOptions), function(type) {
|
||||
_.each(_.keys(heaterOptions), function (type) {
|
||||
if (type === "bed" && !self.hasBed()) {
|
||||
return;
|
||||
}
|
||||
@@ -471,16 +503,39 @@ $(function() {
|
||||
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) : "-";
|
||||
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,
|
||||
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,
|
||||
label:
|
||||
gettext("Target") +
|
||||
" " +
|
||||
heaterOptions[type].name +
|
||||
": " +
|
||||
targetTemp,
|
||||
color: pusher.color(heaterOptions[type].color).tint(0.5).html(),
|
||||
data: targets.length ? targets : [[now, undefined]]
|
||||
});
|
||||
@@ -491,12 +546,15 @@ $(function() {
|
||||
return {max: maxTemps, data: data};
|
||||
};
|
||||
|
||||
self.updateLegend = function(replaceLegendLabel) {
|
||||
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;
|
||||
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);
|
||||
});
|
||||
};
|
||||
@@ -509,13 +567,17 @@ $(function() {
|
||||
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) {
|
||||
if (
|
||||
pos.x < axes.xaxis.min ||
|
||||
pos.x > axes.xaxis.max ||
|
||||
pos.y < axes.yaxis.min ||
|
||||
pos.y > axes.yaxis.max
|
||||
) {
|
||||
// position outside of the graph, show latest temperature in legend
|
||||
resetLegend();
|
||||
} else {
|
||||
// position inside the graph, determine temperature at point and display that in the legend
|
||||
_.each(dataset, function(series, index) {
|
||||
_.each(dataset, function (series, index) {
|
||||
for (i = 0; i < series.data.length; i++) {
|
||||
if (series.data[i][0] > pos.x) {
|
||||
break;
|
||||
@@ -533,7 +595,9 @@ $(function() {
|
||||
} else if (p2 === undefined) {
|
||||
y = p1[1];
|
||||
} else {
|
||||
y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]);
|
||||
y =
|
||||
p1[1] +
|
||||
((p2[1] - p1[1]) * (pos.x - p1[0])) / (p2[0] - p1[0]);
|
||||
}
|
||||
|
||||
replaceLegendLabel(index, series, y, true);
|
||||
@@ -547,24 +611,27 @@ $(function() {
|
||||
self.plot.setupGrid();
|
||||
};
|
||||
|
||||
self.getMaxTemp = function(actuals, targets) {
|
||||
self.getMaxTemp = function (actuals, targets) {
|
||||
var maxTemp = 0;
|
||||
actuals.forEach(function(pair) {
|
||||
if (pair[1] > maxTemp){
|
||||
actuals.forEach(function (pair) {
|
||||
if (pair[1] > maxTemp) {
|
||||
maxTemp = pair[1];
|
||||
}
|
||||
});
|
||||
targets.forEach(function(pair) {
|
||||
if (pair[1] > maxTemp){
|
||||
targets.forEach(function (pair) {
|
||||
if (pair[1] > maxTemp) {
|
||||
maxTemp = pair[1];
|
||||
}
|
||||
});
|
||||
return maxTemp;
|
||||
};
|
||||
|
||||
self.incrementTarget = function(item) {
|
||||
self.incrementTarget = function (item) {
|
||||
var value = item.newTarget();
|
||||
if (value === undefined || (typeof(value) === "string" && value.trim() === "")) {
|
||||
if (
|
||||
value === undefined ||
|
||||
(typeof value === "string" && value.trim() === "")
|
||||
) {
|
||||
value = item.target();
|
||||
}
|
||||
try {
|
||||
@@ -577,9 +644,12 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.decrementTarget = function(item) {
|
||||
self.decrementTarget = function (item) {
|
||||
var value = item.newTarget();
|
||||
if (value === undefined || (typeof(value) === "string" && value.trim() === "")) {
|
||||
if (
|
||||
value === undefined ||
|
||||
(typeof value === "string" && value.trim() === "")
|
||||
) {
|
||||
value = item.target();
|
||||
}
|
||||
try {
|
||||
@@ -594,21 +664,22 @@ $(function() {
|
||||
|
||||
var _sendTimeout = {};
|
||||
|
||||
self.autosendTarget = function(item) {
|
||||
self.autosendTarget = function (item) {
|
||||
if (!self.settingsViewModel.temperature_sendAutomatically()) return;
|
||||
var delay = self.settingsViewModel.temperature_sendAutomaticallyAfter() * 1000;
|
||||
var delay =
|
||||
self.settingsViewModel.temperature_sendAutomaticallyAfter() * 1000;
|
||||
|
||||
var name = item.name();
|
||||
if (_sendTimeout[name]) {
|
||||
window.clearTimeout(_sendTimeout[name]);
|
||||
}
|
||||
_sendTimeout[name] = window.setTimeout(function() {
|
||||
_sendTimeout[name] = window.setTimeout(function () {
|
||||
self.setTarget(item);
|
||||
delete _sendTimeout[name];
|
||||
}, delay);
|
||||
};
|
||||
|
||||
self.clearAutosendTarget = function(item) {
|
||||
self.clearAutosendTarget = function (item) {
|
||||
var name = item.name();
|
||||
if (_sendTimeout[name]) {
|
||||
window.clearTimeout(_sendTimeout[name]);
|
||||
@@ -616,38 +687,39 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.setTarget = function(item, form) {
|
||||
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();
|
||||
if (value === undefined || (typeof value === "string" && value.trim() === ""))
|
||||
return OctoPrintClient.createRejectedDeferred();
|
||||
|
||||
self.clearAutosendTarget(item);
|
||||
return self.setTargetToValue(item, value);
|
||||
};
|
||||
|
||||
// Wrapper of self.setTargetFromProfile() to apply all the temperature from a temperature profile
|
||||
self.setTargetsFromProfile = function(temperatureProfile) {
|
||||
if(temperatureProfile === undefined) {
|
||||
self.setTargetsFromProfile = function (temperatureProfile) {
|
||||
if (temperatureProfile === undefined) {
|
||||
console.log("temperatureProfile is undefined!");
|
||||
return;
|
||||
}
|
||||
|
||||
if(self.hasBed()) {
|
||||
if (self.hasBed()) {
|
||||
self.setTargetFromProfile(self.bedTemp, temperatureProfile);
|
||||
}
|
||||
|
||||
if(self.hasChamber()) {
|
||||
if (self.hasChamber()) {
|
||||
self.setTargetFromProfile(self.chamberTemp, temperatureProfile);
|
||||
}
|
||||
|
||||
self.tools().forEach(function(element) {
|
||||
self.tools().forEach(function (element) {
|
||||
self.setTargetFromProfile(element, temperatureProfile);
|
||||
});
|
||||
};
|
||||
|
||||
self.setTargetFromProfile = function(item, profile) {
|
||||
self.setTargetFromProfile = function (item, profile) {
|
||||
if (!profile) return OctoPrintClient.createRejectedDeferred();
|
||||
|
||||
self.clearAutosendTarget(item);
|
||||
@@ -666,26 +738,26 @@ $(function() {
|
||||
};
|
||||
|
||||
// Wrapper of self.setTargetToZero() to set off all the temperatures
|
||||
self.setTargetsToZero = function() {
|
||||
if(self.hasBed()) {
|
||||
self.setTargetsToZero = function () {
|
||||
if (self.hasBed()) {
|
||||
self.setTargetToZero(self.bedTemp);
|
||||
}
|
||||
|
||||
if(self.hasChamber()) {
|
||||
if (self.hasChamber()) {
|
||||
self.setTargetToZero(self.chamberTemp);
|
||||
}
|
||||
|
||||
self.tools().forEach(function(element) {
|
||||
self.tools().forEach(function (element) {
|
||||
self.setTargetToZero(element);
|
||||
});
|
||||
};
|
||||
|
||||
self.setTargetToZero = function(item) {
|
||||
self.setTargetToZero = function (item) {
|
||||
self.clearAutosendTarget(item);
|
||||
return self.setTargetToValue(item, 0);
|
||||
};
|
||||
|
||||
self.setTargetToValue = function(item, value) {
|
||||
self.setTargetToValue = function (item, value) {
|
||||
self.clearAutosendTarget(item);
|
||||
|
||||
try {
|
||||
@@ -696,24 +768,21 @@ $(function() {
|
||||
|
||||
if (value < 0 || value > 999) return OctoPrintClient.createRejectedDeferred();
|
||||
|
||||
var onSuccess = function() {
|
||||
var onSuccess = function () {
|
||||
item.target(value);
|
||||
item.newTarget("");
|
||||
};
|
||||
|
||||
if (item.key() === "bed") {
|
||||
return self._setBedTemperature(value)
|
||||
.done(onSuccess);
|
||||
return self._setBedTemperature(value).done(onSuccess);
|
||||
} else if (item.key() === "chamber") {
|
||||
return self._setChamberTemperature(value)
|
||||
.done(onSuccess);
|
||||
return self._setChamberTemperature(value).done(onSuccess);
|
||||
} else {
|
||||
return self._setToolTemperature(item.key(), value)
|
||||
.done(onSuccess);
|
||||
return self._setToolTemperature(item.key(), value).done(onSuccess);
|
||||
}
|
||||
};
|
||||
|
||||
self.changeOffset = function(item) {
|
||||
self.changeOffset = function (item) {
|
||||
// copy values
|
||||
self.changingOffset.item = item;
|
||||
self.changingOffset.name(item.name());
|
||||
@@ -723,9 +792,10 @@ $(function() {
|
||||
self.changeOffsetDialog.modal("show");
|
||||
};
|
||||
|
||||
self.incrementChangeOffset = function() {
|
||||
self.incrementChangeOffset = function () {
|
||||
var value = self.changingOffset.newOffset();
|
||||
if (value === undefined || (typeof(value) === "string" && value.trim() === "")) value = self.changingOffset.offset();
|
||||
if (value === undefined || (typeof value === "string" && value.trim() === ""))
|
||||
value = self.changingOffset.offset();
|
||||
try {
|
||||
value = parseInt(value);
|
||||
if (value >= 50) return;
|
||||
@@ -735,9 +805,10 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.decrementChangeOffset = function() {
|
||||
self.decrementChangeOffset = function () {
|
||||
var value = self.changingOffset.newOffset();
|
||||
if (value === undefined || (typeof(value) === "string" && value.trim() === "")) value = self.changingOffset.offset();
|
||||
if (value === undefined || (typeof value === "string" && value.trim() === ""))
|
||||
value = self.changingOffset.offset();
|
||||
try {
|
||||
value = parseInt(value);
|
||||
if (value <= -50) return;
|
||||
@@ -747,91 +818,89 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.deleteChangeOffset = function() {
|
||||
self.deleteChangeOffset = function () {
|
||||
self.changingOffset.newOffset(0);
|
||||
};
|
||||
|
||||
self.confirmChangeOffset = function() {
|
||||
self.confirmChangeOffset = function () {
|
||||
var item = self.changingOffset.item;
|
||||
item.newOffset(self.changingOffset.newOffset());
|
||||
|
||||
self.setOffset(item)
|
||||
.done(function() {
|
||||
self.changeOffsetDialog.modal("hide");
|
||||
self.setOffset(item).done(function () {
|
||||
self.changeOffsetDialog.modal("hide");
|
||||
|
||||
// reset
|
||||
self.changingOffset.offset(0);
|
||||
self.changingOffset.newOffset(0);
|
||||
self.changingOffset.name("");
|
||||
self.changingOffset.item = undefined;
|
||||
})
|
||||
// reset
|
||||
self.changingOffset.offset(0);
|
||||
self.changingOffset.newOffset(0);
|
||||
self.changingOffset.name("");
|
||||
self.changingOffset.item = undefined;
|
||||
});
|
||||
};
|
||||
|
||||
self.setOffset = function(item) {
|
||||
self.setOffset = function (item) {
|
||||
var value = item.newOffset();
|
||||
if (value === undefined || (typeof(value) === "string" && value.trim() === "")) return OctoPrintClient.createRejectedDeferred();
|
||||
if (value === undefined || (typeof value === "string" && value.trim() === ""))
|
||||
return OctoPrintClient.createRejectedDeferred();
|
||||
return self.setOffsetToValue(item, value);
|
||||
};
|
||||
|
||||
self.setOffsetToZero = function(item) {
|
||||
self.setOffsetToZero = function (item) {
|
||||
return self.setOffsetToValue(item, 0);
|
||||
};
|
||||
|
||||
self.setOffsetToValue = function(item, value) {
|
||||
self.setOffsetToValue = function (item, value) {
|
||||
try {
|
||||
value = parseInt(value);
|
||||
} catch (ex) {
|
||||
return OctoPrintClient.createRejectedDeferred();
|
||||
}
|
||||
|
||||
if (value < -50 || value > 50) return OctoPrintClient.createRejectedDeferred();
|
||||
if (value < -50 || value > 50)
|
||||
return OctoPrintClient.createRejectedDeferred();
|
||||
|
||||
var onSuccess = function() {
|
||||
var onSuccess = function () {
|
||||
item.offset(value);
|
||||
item.newOffset("");
|
||||
};
|
||||
|
||||
if (item.key() === "bed") {
|
||||
return self._setBedOffset(value)
|
||||
.done(onSuccess);
|
||||
return self._setBedOffset(value).done(onSuccess);
|
||||
} else if (item.key() === "chamber") {
|
||||
return self._setChamberOffset(value)
|
||||
.done(onSuccess);
|
||||
return self._setChamberOffset(value).done(onSuccess);
|
||||
} else {
|
||||
return self._setToolOffset(item.key(), value)
|
||||
.done(onSuccess);
|
||||
return self._setToolOffset(item.key(), value).done(onSuccess);
|
||||
}
|
||||
};
|
||||
|
||||
self._setToolTemperature = function(tool, temperature) {
|
||||
self._setToolTemperature = function (tool, temperature) {
|
||||
var data = {};
|
||||
data[tool] = parseInt(temperature);
|
||||
return OctoPrint.printer.setToolTargetTemperatures(data);
|
||||
};
|
||||
|
||||
self._setToolOffset = function(tool, offset) {
|
||||
self._setToolOffset = function (tool, offset) {
|
||||
var data = {};
|
||||
data[tool] = parseInt(offset);
|
||||
return OctoPrint.printer.setToolTemperatureOffsets(data);
|
||||
};
|
||||
|
||||
self._setBedTemperature = function(temperature) {
|
||||
self._setBedTemperature = function (temperature) {
|
||||
return OctoPrint.printer.setBedTargetTemperature(parseInt(temperature));
|
||||
};
|
||||
|
||||
self._setBedOffset = function(offset) {
|
||||
self._setBedOffset = function (offset) {
|
||||
return OctoPrint.printer.setBedTemperatureOffset(parseInt(offset));
|
||||
};
|
||||
|
||||
self._setChamberTemperature = function(temperature) {
|
||||
self._setChamberTemperature = function (temperature) {
|
||||
return OctoPrint.printer.setChamberTargetTemperature(parseInt(temperature));
|
||||
};
|
||||
|
||||
self._setChamberOffset = function(offset) {
|
||||
self._setChamberOffset = function (offset) {
|
||||
return OctoPrint.printer.setChamberTemperatureOffset(parseInt(offset));
|
||||
};
|
||||
|
||||
self._replaceLegendLabel = function(index, series, value, emph) {
|
||||
self._replaceLegendLabel = function (index, series, value, emph) {
|
||||
var showFahrenheit = self._shallShowFahrenheit();
|
||||
|
||||
var temp;
|
||||
@@ -848,42 +917,44 @@ $(function() {
|
||||
series.label = series.label.replace(/:.*/, ": " + temp);
|
||||
};
|
||||
|
||||
self._shallShowFahrenheit = function() {
|
||||
return (self.settingsViewModel.settings !== undefined )
|
||||
? self.settingsViewModel.settings.appearance.showFahrenheitAlso()
|
||||
: false;
|
||||
self._shallShowFahrenheit = function () {
|
||||
return self.settingsViewModel.settings !== undefined
|
||||
? self.settingsViewModel.settings.appearance.showFahrenheitAlso()
|
||||
: false;
|
||||
};
|
||||
|
||||
self.handleEnter = function(event, type, item) {
|
||||
self.handleEnter = function (event, type, item) {
|
||||
if (event.keyCode === 13) {
|
||||
if (type === "target") {
|
||||
self.setTarget(item)
|
||||
.done(function() {
|
||||
event.target.blur();
|
||||
});
|
||||
self.setTarget(item).done(function () {
|
||||
event.target.blur();
|
||||
});
|
||||
} else if (type === "offset") {
|
||||
self.confirmChangeOffset();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.handleFocus = function(event, type, item) {
|
||||
self.handleFocus = function (event, type, item) {
|
||||
if (type === "target") {
|
||||
var value = item.newTarget();
|
||||
if (value === undefined || (typeof(value) === "string" && value.trim() === "")) {
|
||||
if (
|
||||
value === undefined ||
|
||||
(typeof value === "string" && value.trim() === "")
|
||||
) {
|
||||
item.newTarget(item.target());
|
||||
}
|
||||
window.setTimeout(function() {
|
||||
window.setTimeout(function () {
|
||||
event.target.select();
|
||||
}, 0);
|
||||
} else if (type === "offset") {
|
||||
window.setTimeout(function() {
|
||||
window.setTimeout(function () {
|
||||
event.target.select();
|
||||
}, 0);
|
||||
}
|
||||
};
|
||||
|
||||
self.initOrUpdate = function() {
|
||||
self.initOrUpdate = function () {
|
||||
if (OctoPrint.coreui.selectedTab !== "#temp" || !$("#temp").is(":visible")) {
|
||||
// do not try to initialize the graph when it's not visible or its sizing will be off
|
||||
return;
|
||||
@@ -896,18 +967,18 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.onAfterTabChange = function() {
|
||||
self.onAfterTabChange = function () {
|
||||
self.initOrUpdate();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onStartup = function () {
|
||||
var graph = $("#temperature-graph");
|
||||
if (graph.length && !OctoPrint.coreui.browser.mobile) {
|
||||
graph.bind("plothover", function (event, pos, item) {
|
||||
graph.bind("plothover", function (event, pos, item) {
|
||||
self.plotHoverPos = pos;
|
||||
if (!self.plotLegendTimeout) {
|
||||
self.plotLegendTimeout = window.setTimeout(function() {
|
||||
self.updateLegend(self._replaceLegendLabel)
|
||||
self.plotLegendTimeout = window.setTimeout(function () {
|
||||
self.updateLegend(self._replaceLegendLabel);
|
||||
}, 50);
|
||||
}
|
||||
});
|
||||
@@ -916,15 +987,14 @@ $(function() {
|
||||
self.changeOffsetDialog = $("#change_offset_dialog");
|
||||
};
|
||||
|
||||
self.onStartupComplete = function() {
|
||||
self.onStartupComplete = function () {
|
||||
self.initOrUpdate();
|
||||
self._printerProfileUpdated();
|
||||
};
|
||||
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
|
||||
self.initOrUpdate();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function TerminalViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -10,9 +10,9 @@ $(function() {
|
||||
self.previousScroll = undefined;
|
||||
|
||||
self.log = ko.observableArray([]);
|
||||
self.log.extend({ throttle: 500 });
|
||||
self.log.extend({throttle: 500});
|
||||
self.plainLogLines = ko.observableArray([]);
|
||||
self.plainLogLines.extend({ throttle: 500 });
|
||||
self.plainLogLines.extend({throttle: 500});
|
||||
|
||||
self.buffer = ko.observable(300);
|
||||
self.upperLimit = ko.observable(1499);
|
||||
@@ -45,27 +45,30 @@ $(function() {
|
||||
self.forceFancyFunctionality = ko.observable(false);
|
||||
self.forceTerminalLogDuringPrinting = ko.observable(false);
|
||||
|
||||
self.fancyFunctionality = ko.pureComputed(function() {
|
||||
self.fancyFunctionality = ko.pureComputed(function () {
|
||||
return self.enableFancyFunctionality() || self.forceFancyFunctionality();
|
||||
});
|
||||
self.terminalLogDuringPrinting = ko.pureComputed(function() {
|
||||
return !self.disableTerminalLogDuringPrinting() || self.forceTerminalLogDuringPrinting();
|
||||
self.terminalLogDuringPrinting = ko.pureComputed(function () {
|
||||
return (
|
||||
!self.disableTerminalLogDuringPrinting() ||
|
||||
self.forceTerminalLogDuringPrinting()
|
||||
);
|
||||
});
|
||||
|
||||
self.displayedLines = ko.pureComputed(function() {
|
||||
self.displayedLines = ko.pureComputed(function () {
|
||||
if (!self.enableFancyFunctionality()) {
|
||||
return self.log();
|
||||
}
|
||||
|
||||
var regex = self.filterRegex();
|
||||
var lineVisible = function(entry) {
|
||||
var lineVisible = function (entry) {
|
||||
return regex == undefined || !entry.line.match(regex);
|
||||
};
|
||||
|
||||
var filtered = false;
|
||||
var result = [];
|
||||
var lines = self.log();
|
||||
_.each(lines, function(entry) {
|
||||
_.each(lines, function (entry) {
|
||||
if (lineVisible(entry)) {
|
||||
result.push(entry);
|
||||
filtered = false;
|
||||
@@ -78,20 +81,20 @@ $(function() {
|
||||
return result;
|
||||
});
|
||||
|
||||
self.plainLogOutput = ko.pureComputed(function() {
|
||||
self.plainLogOutput = ko.pureComputed(function () {
|
||||
if (self.fancyFunctionality()) {
|
||||
return;
|
||||
}
|
||||
return self.plainLogLines().join("\n");
|
||||
});
|
||||
|
||||
self.lineCount = ko.pureComputed(function() {
|
||||
self.lineCount = ko.pureComputed(function () {
|
||||
if (!self.fancyFunctionality()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var regex = self.filterRegex();
|
||||
var lineVisible = function(entry) {
|
||||
var lineVisible = function (entry) {
|
||||
return regex == undefined || !entry.line.match(regex);
|
||||
};
|
||||
|
||||
@@ -102,69 +105,96 @@ $(function() {
|
||||
|
||||
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});
|
||||
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});
|
||||
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});
|
||||
return _.sprintf(
|
||||
gettext("showing %(displayed)d lines (buffer full)"),
|
||||
{displayed: displayed}
|
||||
);
|
||||
} else {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines"), {displayed: displayed});
|
||||
return _.sprintf(gettext("showing %(displayed)d lines"), {
|
||||
displayed: displayed
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
self.autoscrollEnabled.subscribe(function(newValue) {
|
||||
self.autoscrollEnabled.subscribe(function (newValue) {
|
||||
if (newValue) {
|
||||
self.log(self.log.slice(-self.buffer()));
|
||||
}
|
||||
});
|
||||
|
||||
self.activeFilters = ko.observableArray([]);
|
||||
self.activeFilters.subscribe(function(e) {
|
||||
self.activeFilters.subscribe(function (e) {
|
||||
self.updateFilterRegex();
|
||||
});
|
||||
|
||||
self.blacklist=[];
|
||||
self.settings.feature_autoUppercaseBlacklist.subscribe(function(newValue) {
|
||||
self.blacklist = [];
|
||||
self.settings.feature_autoUppercaseBlacklist.subscribe(function (newValue) {
|
||||
self.blacklist = splitTextToArray(newValue, ",", true);
|
||||
});
|
||||
|
||||
self._reenableFancyTimer = undefined;
|
||||
self._reenableUnfancyTimer = undefined;
|
||||
self._disableFancy = function(difference) {
|
||||
log.warn("Terminal: Detected slow client (needed " + difference + "ms for processing new log data), disabling fancy terminal functionality");
|
||||
self._disableFancy = function (difference) {
|
||||
log.warn(
|
||||
"Terminal: Detected slow client (needed " +
|
||||
difference +
|
||||
"ms for processing new log data), disabling fancy terminal functionality"
|
||||
);
|
||||
if (self._reenableFancyTimer) {
|
||||
window.clearTimeout(self._reenableFancyTimer);
|
||||
self._reenableFancyTimer = undefined;
|
||||
}
|
||||
self.enableFancyFunctionality(false);
|
||||
};
|
||||
self._reenableFancy = function(difference) {
|
||||
self._reenableFancy = function (difference) {
|
||||
if (self._reenableFancyTimer) return;
|
||||
self._reenableFancyTimer = window.setTimeout(function() {
|
||||
log.info("Terminal: Client speed recovered, enabling fancy terminal functionality");
|
||||
self._reenableFancyTimer = window.setTimeout(function () {
|
||||
log.info(
|
||||
"Terminal: Client speed recovered, enabling fancy terminal functionality"
|
||||
);
|
||||
self.enableFancyFunctionality(true);
|
||||
}, self.reenableTimeout);
|
||||
};
|
||||
self._disableUnfancy = function(difference) {
|
||||
log.warn("Terminal: Detected very slow client (needed " + difference + "ms for processing new log data), completely disabling terminal output during printing");
|
||||
self._disableUnfancy = function (difference) {
|
||||
log.warn(
|
||||
"Terminal: Detected very slow client (needed " +
|
||||
difference +
|
||||
"ms for processing new log data), completely disabling terminal output during printing"
|
||||
);
|
||||
if (self._reenableUnfancyTimer) {
|
||||
window.clearTimeout(self._reenableUnfancyTimer);
|
||||
self._reenableUnfancyTimer = undefined;
|
||||
}
|
||||
self.disableTerminalLogDuringPrinting(true);
|
||||
};
|
||||
self._reenableUnfancy = function() {
|
||||
self._reenableUnfancy = function () {
|
||||
if (self._reenableUnfancyTimer) return;
|
||||
self._reenableUnfancyTimer = window.setTimeout(function() {
|
||||
log.info("Terminal: Client speed recovered, enabling terminal output during printing");
|
||||
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.fromCurrentData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
|
||||
var start = new Date().getTime();
|
||||
@@ -192,12 +222,12 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self.fromHistoryData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
self._processHistoryLogData(data.logs);
|
||||
};
|
||||
|
||||
self._processCurrentLogData = function(data) {
|
||||
self._processCurrentLogData = function (data) {
|
||||
var length = self.log().length;
|
||||
if (length >= self.upperLimit()) {
|
||||
return;
|
||||
@@ -205,28 +235,36 @@ $(function() {
|
||||
|
||||
if (!self.terminalLogDuringPrinting() && self.isPrinting()) {
|
||||
var last = self.plainLogLines()[self.plainLogLines().length - 1];
|
||||
var disabled = "--- client too slow, log output disabled while printing ---";
|
||||
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;
|
||||
var newData =
|
||||
data.length + length > self.upperLimit()
|
||||
? data.slice(0, self.upperLimit() - length)
|
||||
: data;
|
||||
if (!newData) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.fancyFunctionality()) {
|
||||
// lite version of the terminal - text output only
|
||||
self.plainLogLines(self.plainLogLines().concat(newData).slice(-self.buffer()));
|
||||
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) }));
|
||||
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"));
|
||||
@@ -240,20 +278,24 @@ $(function() {
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self._processHistoryLogData = function(data) {
|
||||
self._processHistoryLogData = function (data) {
|
||||
self.plainLogLines(data);
|
||||
self.log(_.map(data, function(line) { return self._toInternalFormat(line) }));
|
||||
self.log(
|
||||
_.map(data, function (line) {
|
||||
return self._toInternalFormat(line);
|
||||
})
|
||||
);
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self._toInternalFormat = function(line, type) {
|
||||
self._toInternalFormat = function (line, type) {
|
||||
if (type == undefined) {
|
||||
type = "line";
|
||||
}
|
||||
return {line: escapeUnprintableCharacters(line), type: type}
|
||||
return {line: escapeUnprintableCharacters(line), type: type};
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self._processStateData = function (data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
@@ -263,7 +305,7 @@ $(function() {
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
self.updateFilterRegex = function() {
|
||||
self.updateFilterRegex = function () {
|
||||
var filterRegexStr = self.activeFilters().join("|").trim();
|
||||
if (filterRegexStr == "") {
|
||||
self.filterRegex(undefined);
|
||||
@@ -273,21 +315,28 @@ $(function() {
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self.updateOutput = function() {
|
||||
if (self.tabActive && OctoPrint.coreui.browserTabVisible && self.autoscrollEnabled()) {
|
||||
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 container = self.fancyFunctionality()
|
||||
? $("#terminal-output")
|
||||
: $("#terminal-output-lowfi");
|
||||
var pos = container.scrollTop();
|
||||
var scrollingUp = self.previousScroll !== undefined && pos < self.previousScroll;
|
||||
var scrollingUp =
|
||||
self.previousScroll !== undefined && pos < self.previousScroll;
|
||||
|
||||
if (self.autoscrollEnabled() && scrollingUp) {
|
||||
var maxScroll = container[0].scrollHeight - container[0].offsetHeight;
|
||||
|
||||
if (pos <= maxScroll ) {
|
||||
if (pos <= maxScroll) {
|
||||
self.autoscrollEnabled(false);
|
||||
}
|
||||
}
|
||||
@@ -295,7 +344,7 @@ $(function() {
|
||||
self.previousScroll = pos;
|
||||
}, 250);
|
||||
|
||||
self.gotoTerminalCommand = function() {
|
||||
self.gotoTerminalCommand = function () {
|
||||
// skip if user highlights text.
|
||||
var sel = getSelection().toString();
|
||||
if (sel) {
|
||||
@@ -305,7 +354,7 @@ $(function() {
|
||||
$("#terminal-command").focus();
|
||||
};
|
||||
|
||||
self.toggleAutoscroll = function() {
|
||||
self.toggleAutoscroll = function () {
|
||||
self.autoscrollEnabled(!self.autoscrollEnabled());
|
||||
|
||||
if (self.autoscrollEnabled()) {
|
||||
@@ -313,21 +362,25 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.selectAll = function() {
|
||||
var container = self.fancyFunctionality() ? $("#terminal-output") : $("#terminal-output-lowfi");
|
||||
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");
|
||||
self.scrollToEnd = function () {
|
||||
var container = self.fancyFunctionality()
|
||||
? $("#terminal-output")
|
||||
: $("#terminal-output-lowfi");
|
||||
if (container.length) {
|
||||
container.scrollTop(container[0].scrollHeight);
|
||||
}
|
||||
};
|
||||
|
||||
self.copyAll = function() {
|
||||
self.copyAll = function () {
|
||||
var lines;
|
||||
|
||||
if (self.fancyFunctionality()) {
|
||||
@@ -339,7 +392,7 @@ $(function() {
|
||||
copyToClipboard(lines.join("\n"));
|
||||
};
|
||||
|
||||
self.clearAllLogs = function() {
|
||||
self.clearAllLogs = function () {
|
||||
self.log([]);
|
||||
self.plainLogLines([]);
|
||||
};
|
||||
@@ -351,7 +404,7 @@ $(function() {
|
||||
// - 4: command parameters incl. leading whitespace, if any. Example: "", "", "", " test"
|
||||
var commandRe = /^(([gmt][0-9]+)(\.[0-9+])?)(\s.*)?/i;
|
||||
|
||||
self.sendCommand = function() {
|
||||
self.sendCommand = function () {
|
||||
var command = self.command();
|
||||
if (!command) {
|
||||
return;
|
||||
@@ -363,41 +416,54 @@ $(function() {
|
||||
var fullCode = commandMatch[1].toUpperCase(); // full code incl. sub code
|
||||
var mainCode = commandMatch[2].toUpperCase(); // main code only without sub code
|
||||
|
||||
if (self.blacklist.indexOf(mainCode) < 0 && self.blacklist.indexOf(fullCode) < 0) {
|
||||
if (
|
||||
self.blacklist.indexOf(mainCode) < 0 &&
|
||||
self.blacklist.indexOf(fullCode) < 0
|
||||
) {
|
||||
// full or main code not on blacklist -> upper case the whole command
|
||||
commandToSend = commandToSend.toUpperCase();
|
||||
} else {
|
||||
// full or main code on blacklist -> only upper case that and leave parameters as is
|
||||
commandToSend = fullCode + (commandMatch[4] !== undefined ? commandMatch[4] : "");
|
||||
commandToSend =
|
||||
fullCode + (commandMatch[4] !== undefined ? commandMatch[4] : "");
|
||||
}
|
||||
}
|
||||
|
||||
if (commandToSend) {
|
||||
OctoPrint.control.sendGcode(commandToSend)
|
||||
.done(function() {
|
||||
self.cmdHistory.push(command);
|
||||
self.cmdHistory.slice(-300); // just to set a sane limit to how many manually entered commands will be saved...
|
||||
self.cmdHistoryIdx = self.cmdHistory.length;
|
||||
self.command("");
|
||||
});
|
||||
OctoPrint.control.sendGcode(commandToSend).done(function () {
|
||||
self.cmdHistory.push(command);
|
||||
self.cmdHistory.slice(-300); // just to set a sane limit to how many manually entered commands will be saved...
|
||||
self.cmdHistoryIdx = self.cmdHistory.length;
|
||||
self.command("");
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
self.fakeAck = function() {
|
||||
self.fakeAck = function () {
|
||||
OctoPrint.connection.fakeAck();
|
||||
};
|
||||
|
||||
self.handleKeyDown = function(event) {
|
||||
self.handleKeyDown = function (event) {
|
||||
var keyCode = event.keyCode;
|
||||
|
||||
if (keyCode == 38 || keyCode == 40) {
|
||||
if (keyCode == 38 && self.cmdHistory.length > 0 && self.cmdHistoryIdx > 0) {
|
||||
if (
|
||||
keyCode == 38 &&
|
||||
self.cmdHistory.length > 0 &&
|
||||
self.cmdHistoryIdx > 0
|
||||
) {
|
||||
self.cmdHistoryIdx--;
|
||||
} else if (keyCode == 40 && self.cmdHistoryIdx < self.cmdHistory.length - 1) {
|
||||
} else if (
|
||||
keyCode == 40 &&
|
||||
self.cmdHistoryIdx < self.cmdHistory.length - 1
|
||||
) {
|
||||
self.cmdHistoryIdx++;
|
||||
}
|
||||
|
||||
if (self.cmdHistoryIdx >= 0 && self.cmdHistoryIdx < self.cmdHistory.length) {
|
||||
if (
|
||||
self.cmdHistoryIdx >= 0 &&
|
||||
self.cmdHistoryIdx < self.cmdHistory.length
|
||||
) {
|
||||
self.command(self.cmdHistory[self.cmdHistoryIdx]);
|
||||
}
|
||||
|
||||
@@ -411,7 +477,7 @@ $(function() {
|
||||
return true;
|
||||
};
|
||||
|
||||
self.handleKeyUp = function(event) {
|
||||
self.handleKeyUp = function (event) {
|
||||
if (event.keyCode == 13) {
|
||||
self.sendCommand();
|
||||
}
|
||||
@@ -420,15 +486,14 @@ $(function() {
|
||||
return true;
|
||||
};
|
||||
|
||||
self.onAfterTabChange = function(current, previous) {
|
||||
self.onAfterTabChange = function (current, previous) {
|
||||
self.tabActive = current == "#term";
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self.onBrowserTabVisibilityChange = function(status) {
|
||||
self.onBrowserTabVisibilityChange = function (status) {
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function TimelapseViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -25,7 +25,7 @@ $(function() {
|
||||
self.renderProgress = ko.observable();
|
||||
self.renderTarget = ko.observable();
|
||||
self.renderAnimation = ko.observable(false);
|
||||
self.renderProgressString = ko.pureComputed(function() {
|
||||
self.renderProgressString = ko.pureComputed(function () {
|
||||
if (!self.renderTarget()) {
|
||||
return 0;
|
||||
}
|
||||
@@ -40,21 +40,25 @@ $(function() {
|
||||
|
||||
return self.renderProgress();
|
||||
});
|
||||
self.renderProgressBarString = ko.pureComputed(function() {
|
||||
self.renderProgressBarString = ko.pureComputed(function () {
|
||||
if (!self.renderTarget()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (self.renderAnimation()) {
|
||||
return _.sprintf(gettext("Rendering %(target)s..."), {target: self.renderTarget()});
|
||||
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});
|
||||
return _.sprintf(gettext("Rendering %(target)s... (%(progress)d%%)"), {
|
||||
target: self.renderTarget(),
|
||||
progress: progress
|
||||
});
|
||||
});
|
||||
|
||||
self.serverConfig = ko.observable();
|
||||
@@ -73,46 +77,50 @@ $(function() {
|
||||
self.markedForFileDeletion = ko.observableArray([]);
|
||||
self.markedForUnrenderedDeletion = ko.observableArray([]);
|
||||
|
||||
self.isTemporary = ko.pureComputed(function() {
|
||||
self.isTemporary = ko.pureComputed(function () {
|
||||
return self.isDirty() && !self.persist();
|
||||
});
|
||||
|
||||
self.isBusy = ko.pureComputed(function() {
|
||||
self.isBusy = ko.pureComputed(function () {
|
||||
return self.isPrinting() || self.isPaused();
|
||||
});
|
||||
|
||||
self.timelapseTypeSelected = ko.pureComputed(function() {
|
||||
return ("off" !== self.timelapseType());
|
||||
self.timelapseTypeSelected = ko.pureComputed(function () {
|
||||
return "off" !== self.timelapseType();
|
||||
});
|
||||
self.intervalInputEnabled = ko.pureComputed(function() {
|
||||
return ("timed" === 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.saveButtonEnabled = ko.pureComputed(function () {
|
||||
return (
|
||||
self.loginState.hasPermission(self.access.permissions.TIMELAPSE_ADMIN) &&
|
||||
self.isDirty() &&
|
||||
!self.isPrinting()
|
||||
);
|
||||
});
|
||||
self.resetButtonEnabled = ko.pureComputed(function() {
|
||||
self.resetButtonEnabled = ko.pureComputed(function () {
|
||||
return self.saveButtonEnabled() && self.serverConfig() !== undefined;
|
||||
});
|
||||
|
||||
self.timelapseType.subscribe(function() {
|
||||
self.timelapseType.subscribe(function () {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.timelapseTimedInterval.subscribe(function() {
|
||||
self.timelapseTimedInterval.subscribe(function () {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.timelapsePostRoll.subscribe(function() {
|
||||
self.timelapsePostRoll.subscribe(function () {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.timelapseFps.subscribe(function() {
|
||||
self.timelapseFps.subscribe(function () {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.timelapseRetractionZHop.subscribe(function(newValue) {
|
||||
self.timelapseRetractionZHop.subscribe(function (newValue) {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.timelapseMinDelay.subscribe(function() {
|
||||
self.timelapseMinDelay.subscribe(function () {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.persist.subscribe(function() {
|
||||
self.persist.subscribe(function () {
|
||||
self.isDirty(true);
|
||||
});
|
||||
|
||||
@@ -120,27 +128,28 @@ $(function() {
|
||||
self.listHelper = new ItemListHelper(
|
||||
"timelapseFiles",
|
||||
{
|
||||
"name": function(a, b) {
|
||||
name: function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase())
|
||||
return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase())
|
||||
return 1;
|
||||
return 0;
|
||||
},
|
||||
"date": function(a, b) {
|
||||
date: function (a, b) {
|
||||
// sorts descending
|
||||
if (a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
},
|
||||
"size": function(a, b) {
|
||||
size: function (a, b) {
|
||||
// sorts descending
|
||||
if (a["bytes"] > b["bytes"]) return -1;
|
||||
if (a["bytes"] < b["bytes"]) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
{},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
@@ -151,42 +160,42 @@ $(function() {
|
||||
self.unrenderedListHelper = new ItemListHelper(
|
||||
"unrenderedTimelapseFiles",
|
||||
{
|
||||
"name": function(a, b) {
|
||||
name: function (a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase())
|
||||
return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase())
|
||||
return 1;
|
||||
return 0;
|
||||
},
|
||||
"creation": function(a, b) {
|
||||
creation: function (a, b) {
|
||||
// sorts descending
|
||||
if (a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
},
|
||||
"size": function(a, b) {
|
||||
size: function (a, b) {
|
||||
// sorts descending
|
||||
if (a["bytes"] > b["bytes"]) return -1;
|
||||
if (a["bytes"] < b["bytes"]) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
{},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
CONFIG_TIMELAPSEFILESPERPAGE
|
||||
);
|
||||
|
||||
self.requestData = function() {
|
||||
self.requestData = function () {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_LIST))
|
||||
return;
|
||||
|
||||
OctoPrint.timelapse.get(true)
|
||||
.done(self.fromResponse);
|
||||
OctoPrint.timelapse.get(true).done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.fromResponse = function (response) {
|
||||
var config = response.config;
|
||||
if (config === undefined) return;
|
||||
|
||||
@@ -203,22 +212,34 @@ $(function() {
|
||||
self.serverConfig(response.config);
|
||||
};
|
||||
|
||||
self.fromConfig = function(config) {
|
||||
self.fromConfig = function (config) {
|
||||
self.timelapseType(config.type);
|
||||
|
||||
if (config.type === "timed" && config.interval !== undefined && config.interval > 0) {
|
||||
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) {
|
||||
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) {
|
||||
if (
|
||||
config.type === "zchange" &&
|
||||
config.minDelay !== undefined &&
|
||||
config.minDelay >= 0
|
||||
) {
|
||||
self.timelapseMinDelay(config.minDelay);
|
||||
} else {
|
||||
self.timelapseMinDelay(self.defaultMinDelay);
|
||||
@@ -240,15 +261,15 @@ $(function() {
|
||||
self.isDirty(false);
|
||||
};
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self.fromCurrentData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self.fromHistoryData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self._processStateData = function (data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
@@ -258,46 +279,69 @@ $(function() {
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
self.markFilesOnPage = function() {
|
||||
self.markedForFileDeletion(_.uniq(self.markedForFileDeletion().concat(_.map(self.listHelper.paginatedItems(), "name"))));
|
||||
self.markFilesOnPage = function () {
|
||||
self.markedForFileDeletion(
|
||||
_.uniq(
|
||||
self
|
||||
.markedForFileDeletion()
|
||||
.concat(_.map(self.listHelper.paginatedItems(), "name"))
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
self.markAllFiles = function() {
|
||||
self.markAllFiles = function () {
|
||||
self.markedForFileDeletion(_.map(self.listHelper.allItems, "name"));
|
||||
};
|
||||
|
||||
self.clearMarkedFiles = function() {
|
||||
self.clearMarkedFiles = function () {
|
||||
self.markedForFileDeletion.removeAll();
|
||||
};
|
||||
|
||||
self.isTimelapseViewable = function(data){
|
||||
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;
|
||||
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.off("hidden.bs.modal").on("hidden.bs.modal", function () {
|
||||
$(this).attr("src", "");
|
||||
});
|
||||
previewModal.modal("show");
|
||||
}
|
||||
};
|
||||
|
||||
self.removeFile = function(filename) {
|
||||
self.removeFile = function (filename) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_DELETE))
|
||||
return;
|
||||
|
||||
var perform = function() {
|
||||
OctoPrint.timelapse.delete(filename)
|
||||
.done(function() {
|
||||
var perform = function () {
|
||||
OctoPrint.timelapse
|
||||
.delete(filename)
|
||||
.done(function () {
|
||||
self.markedForFileDeletion.remove(filename);
|
||||
self.requestData()
|
||||
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>');
|
||||
.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,
|
||||
@@ -307,97 +351,156 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to delete timelapse file \"%(name)s\"."), {name: _.escape(filename)}),
|
||||
perform)
|
||||
showConfirmationDialog(
|
||||
_.sprintf(gettext('You are about to delete timelapse file "%(name)s".'), {
|
||||
name: _.escape(filename)
|
||||
}),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.removeMarkedFiles = function() {
|
||||
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();
|
||||
});
|
||||
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);
|
||||
showConfirmationDialog(
|
||||
_.sprintf(gettext("You are about to delete %(count)d timelapse files."), {
|
||||
count: self.markedForFileDeletion().length
|
||||
}),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.markUnrenderedOnPage = function() {
|
||||
self.markedForUnrenderedDeletion(_.uniq(self.markedForUnrenderedDeletion().concat(_.map(self.unrenderedListHelper.paginatedItems(), "name"))));
|
||||
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.markAllUnrendered = function () {
|
||||
self.markedForUnrenderedDeletion(
|
||||
_.map(self.unrenderedListHelper.allItems, "name")
|
||||
);
|
||||
};
|
||||
|
||||
self.clearMarkedUnrendered = function() {
|
||||
self.clearMarkedUnrendered = function () {
|
||||
self.markedForUnrenderedDeletion.removeAll();
|
||||
};
|
||||
|
||||
self.removeUnrendered = function(name) {
|
||||
self.removeUnrendered = function (name) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_DELETE))
|
||||
return;
|
||||
|
||||
var perform = function() {
|
||||
OctoPrint.timelapse.deleteUnrendered(name)
|
||||
.done(function() {
|
||||
self.markedForUnrenderedDeletion.remove(name);
|
||||
self.requestData();
|
||||
});
|
||||
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)
|
||||
showConfirmationDialog(
|
||||
_.sprintf(
|
||||
gettext('You are about to delete unrendered timelapse "%(name)s".'),
|
||||
{name: _.escape(name)}
|
||||
),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.removeMarkedUnrendered = function() {
|
||||
self.removeMarkedUnrendered = function () {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_DELETE))
|
||||
return;
|
||||
|
||||
var perform = function() {
|
||||
self._bulkRemove(self.markedForUnrenderedDeletion(), "unrendered")
|
||||
.done(function() {
|
||||
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);
|
||||
showConfirmationDialog(
|
||||
_.sprintf(
|
||||
gettext("You are about to delete %(count)d unrendered timelapses."),
|
||||
{count: self.markedForUnrenderedDeletion().length}
|
||||
),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self._bulkRemove = function(files, type) {
|
||||
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);
|
||||
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)});
|
||||
.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);
|
||||
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);
|
||||
.fail(function () {
|
||||
deferred.notify(
|
||||
_.sprintf(
|
||||
gettext(
|
||||
"Deletion of %(filename)s failed, continuing..."
|
||||
),
|
||||
{filename: _.escape(filename)}
|
||||
),
|
||||
false
|
||||
);
|
||||
});
|
||||
}
|
||||
};
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
@@ -415,36 +518,34 @@ $(function() {
|
||||
showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(files, function(filename) {
|
||||
_.each(files, function (filename) {
|
||||
var request = handler(filename);
|
||||
requests.push(request)
|
||||
requests.push(request);
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways)).done(function () {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
|
||||
.done(function() {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
self.renderUnrendered = function(name) {
|
||||
self.renderUnrendered = function (name) {
|
||||
if (!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_ADMIN))
|
||||
return;
|
||||
|
||||
OctoPrint.timelapse.renderUnrendered(name)
|
||||
.done(self.requestData);
|
||||
OctoPrint.timelapse.renderUnrendered(name).done(self.requestData);
|
||||
};
|
||||
|
||||
self.save = function() {
|
||||
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()
|
||||
type: self.timelapseType(),
|
||||
postRoll: self.timelapsePostRoll(),
|
||||
fps: self.timelapseFps(),
|
||||
save: self.persist()
|
||||
};
|
||||
|
||||
if (self.timelapseType() === "timed") {
|
||||
@@ -456,23 +557,22 @@ $(function() {
|
||||
payload["minDelay"] = self.timelapseMinDelay();
|
||||
}
|
||||
|
||||
OctoPrint.timelapse.saveConfig(payload)
|
||||
.done(self.fromResponse);
|
||||
OctoPrint.timelapse.saveConfig(payload).done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.reset = function() {
|
||||
self.reset = function () {
|
||||
if (self.serverConfig() === undefined) return;
|
||||
self.fromConfig(self.serverConfig());
|
||||
};
|
||||
|
||||
self.displayTimelapsePopup = function(options) {
|
||||
self.displayTimelapsePopup = function (options) {
|
||||
if (self.timelapsePopup !== undefined) {
|
||||
self.timelapsePopup.remove();
|
||||
}
|
||||
|
||||
_.extend(options, {
|
||||
callbacks: {
|
||||
before_close: function(notice) {
|
||||
before_close: function (notice) {
|
||||
if (self.timelapsePopup === notice) {
|
||||
self.timelapsePopup = undefined;
|
||||
}
|
||||
@@ -483,27 +583,45 @@ $(function() {
|
||||
self.timelapsePopup = new PNotify(options);
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.onDataUpdaterReconnect = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventPostRollStart = function(payload) {
|
||||
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..."));
|
||||
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);
|
||||
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);
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -518,23 +636,36 @@ $(function() {
|
||||
self._warnAboutCaptureFailThreshold = 3;
|
||||
self._warnAboutCaptureFailCounter = 0;
|
||||
self._warnedAboutCaptureFail = false;
|
||||
self.onEventPrintStarted = function(payload) {
|
||||
self.onEventPrintStarted = function (payload) {
|
||||
self._warnAboutCaptureFailCounter = 0;
|
||||
self._warnedAboutCaptureFail = false;
|
||||
};
|
||||
self.onEventCaptureDone = function(payload) {
|
||||
self.onEventCaptureDone = function (payload) {
|
||||
self._warnAboutCaptureFailCounter = 0;
|
||||
self._warnedAboutCaptureFail = false;
|
||||
};
|
||||
self.onEventCaptureFailed = function(payload) {
|
||||
self.onEventCaptureFailed = function (payload) {
|
||||
self._warnAboutCaptureFailCounter++;
|
||||
if (self._warnedAboutCaptureFail || self._warnAboutCaptureFailCounter <= self._warnAboutCaptureFailThreshold) {
|
||||
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 URL configured correctly and the camera on?");
|
||||
html += pnotifyAdditionalInfo('Snapshot URL: <pre style="overflow: auto">' + payload.url + '</pre>Error: <pre style="overflow: auto">' + payload.error + '</pre>');
|
||||
var html =
|
||||
"<p>" +
|
||||
gettext(
|
||||
"Failed repeatedly to capture timelapse frame from webcam - is the snapshot URL configured correctly and the camera on?"
|
||||
);
|
||||
html += pnotifyAdditionalInfo(
|
||||
'Snapshot URL: <pre style="overflow: auto">' +
|
||||
payload.url +
|
||||
'</pre>Error: <pre style="overflow: auto">' +
|
||||
payload.error +
|
||||
"</pre>"
|
||||
);
|
||||
new PNotify({
|
||||
title: gettext("Could not capture snapshots"),
|
||||
text: html,
|
||||
@@ -543,10 +674,15 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.onEventMovieRendering = function(payload) {
|
||||
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)}),
|
||||
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
|
||||
});
|
||||
|
||||
@@ -555,24 +691,53 @@ $(function() {
|
||||
self.renderAnimation(true);
|
||||
};
|
||||
|
||||
self.onRenderProgress = function(percentage) {
|
||||
self.onRenderProgress = function (percentage) {
|
||||
self.renderProgress(percentage);
|
||||
self.renderAnimation(false);
|
||||
};
|
||||
|
||||
self.onEventMovieFailed = function(payload) {
|
||||
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 URL configured correctly?"), {movie_prefix: _.escape(payload.movie_prefix)}) + "</p>";
|
||||
} else if (payload.reason = "returncode") {
|
||||
html =
|
||||
"<p>" +
|
||||
_.sprintf(
|
||||
gettext(
|
||||
"Rendering of timelapse %(movie_prefix)s is not possible since no frames were captured. Is the snapshot URL 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>');
|
||||
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>";
|
||||
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({
|
||||
@@ -587,13 +752,16 @@ $(function() {
|
||||
self.renderAnimation(false);
|
||||
};
|
||||
|
||||
self.onEventMovieDone = function(payload) {
|
||||
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)}),
|
||||
text: _.sprintf(
|
||||
gettext("New timelapse %(movie_prefix)s is done rendering."),
|
||||
{movie_prefix: _.escape(payload.movie_prefix)}
|
||||
),
|
||||
type: "success",
|
||||
callbacks: {
|
||||
before_close: function(notice) {
|
||||
before_close: function (notice) {
|
||||
if (self.timelapsePopup === notice) {
|
||||
self.timelapsePopup = undefined;
|
||||
}
|
||||
@@ -607,11 +775,11 @@ $(function() {
|
||||
self.renderAnimation(false);
|
||||
};
|
||||
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
|
||||
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
|
||||
self.requestData();
|
||||
|
||||
self.renderProgressBar = $("#render_progress");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
@@ -1,20 +1,38 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function UiStateViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loading = ko.observable(CONFIG_LOADINGANIMATION);
|
||||
self.loading_error = ko.observable(false);
|
||||
self.visible = ko.pureComputed(function() {
|
||||
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.");
|
||||
self.showLoadingError = function (error) {
|
||||
log.error(
|
||||
"Loading error: " +
|
||||
error +
|
||||
" Please check prior messages and 'octoprint.log' for possible reasons."
|
||||
);
|
||||
|
||||
// we can't do this with bindings since the bindings are not initialized yet if we need this
|
||||
$("#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();
|
||||
$("#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();
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,31 +1,43 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function UsersViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.access = parameters[0];
|
||||
|
||||
self.deprecatedUsersMethod = function(oldFct) {
|
||||
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);
|
||||
});
|
||||
OctoPrintClient.deprecatedMethod(
|
||||
self,
|
||||
"UsersViewModel",
|
||||
oldFct,
|
||||
"AccessViewModel.users",
|
||||
newFct,
|
||||
function () {
|
||||
self.access.users[newFct](this.arguments);
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
self.deprecatedUsersVariable = function(oldVar) {
|
||||
self.deprecatedUsersVariable = function (oldVar) {
|
||||
var newVar = oldVar;
|
||||
if (arguments.length === 2) {
|
||||
newVar = arguments[1];
|
||||
}
|
||||
|
||||
OctoPrintClient.deprecatedVariable(self, "UsersViewModel", oldVar, "AccessViewModel.users", newVar,
|
||||
function() {
|
||||
OctoPrintClient.deprecatedVariable(
|
||||
self,
|
||||
"UsersViewModel",
|
||||
oldVar,
|
||||
"AccessViewModel.users",
|
||||
newVar,
|
||||
function () {
|
||||
return self.access.users[newVar];
|
||||
},
|
||||
function(val) {
|
||||
function (val) {
|
||||
self.access.users[newVar] = val;
|
||||
}
|
||||
);
|
||||
@@ -48,7 +60,6 @@ $(function() {
|
||||
|
||||
self.deprecatedUsersVariable("editorPasswordMismatch");
|
||||
|
||||
|
||||
self.deprecatedUsersMethod("requestData");
|
||||
self.deprecatedUsersMethod("fromResponse");
|
||||
self.deprecatedUsersMethod("showAddUserDialog");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function UserSettingsViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -9,10 +9,18 @@ $(function() {
|
||||
|
||||
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;
|
||||
})));
|
||||
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);
|
||||
@@ -21,7 +29,7 @@ $(function() {
|
||||
self.interface_language = ko.observable(undefined);
|
||||
|
||||
self.currentUser = ko.observable(undefined);
|
||||
self.currentUser.subscribe(function(newUser) {
|
||||
self.currentUser.subscribe(function (newUser) {
|
||||
self.access_password(undefined);
|
||||
self.access_repeatedPassword(undefined);
|
||||
self.access_apikey(undefined);
|
||||
@@ -29,115 +37,132 @@ $(function() {
|
||||
|
||||
if (newUser !== undefined) {
|
||||
self.access_apikey(newUser.apikey);
|
||||
if (newUser.settings.hasOwnProperty("interface") && newUser.settings.interface.hasOwnProperty("language")) {
|
||||
if (
|
||||
newUser.settings.hasOwnProperty("interface") &&
|
||||
newUser.settings.interface.hasOwnProperty("language")
|
||||
) {
|
||||
self.interface_language(newUser.settings.interface.language);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
self.passwordMismatch = ko.pureComputed(function() {
|
||||
self.passwordMismatch = ko.pureComputed(function () {
|
||||
return self.access_password() !== self.access_repeatedPassword();
|
||||
});
|
||||
|
||||
self.show = function(user) {
|
||||
self.show = function (user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
if (user === undefined) {
|
||||
user = self.loginState.currentUser();
|
||||
}
|
||||
|
||||
var process = function(user) {
|
||||
var process = function (user) {
|
||||
self.currentUser(user);
|
||||
self.userSettingsDialog.modal("show");
|
||||
};
|
||||
|
||||
// make sure we have the current user data, see #2534
|
||||
OctoPrint.access.users.get(user.name)
|
||||
.done(function(data) {
|
||||
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");
|
||||
.fail(function () {
|
||||
log.warn(
|
||||
"Could not fetch current user data, proceeding with client side data copy"
|
||||
);
|
||||
process(user);
|
||||
});
|
||||
};
|
||||
|
||||
self.save = function() {
|
||||
self.save = function () {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
if (self.access_password() && !self.passwordMismatch()) {
|
||||
self.users.updatePassword(self.currentUser().name, self.access_password(), function(){});
|
||||
self.users.updatePassword(
|
||||
self.currentUser().name,
|
||||
self.access_password(),
|
||||
function () {}
|
||||
);
|
||||
}
|
||||
|
||||
var settings = {
|
||||
"interface": {
|
||||
"language": self.interface_language()
|
||||
interface: {
|
||||
language: self.interface_language()
|
||||
}
|
||||
};
|
||||
self.updateSettings(self.currentUser().name, settings)
|
||||
.done(function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.userSettingsDialog.modal("hide");
|
||||
self.loginState.reloadUser();
|
||||
});
|
||||
self.updateSettings(self.currentUser().name, settings).done(function () {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
self.userSettingsDialog.modal("hide");
|
||||
self.loginState.reloadUser();
|
||||
});
|
||||
};
|
||||
|
||||
self.copyApikey = function() {
|
||||
self.copyApikey = function () {
|
||||
copyToClipboard(self.access_apikey());
|
||||
};
|
||||
|
||||
self.generateApikey = function() {
|
||||
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);
|
||||
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);
|
||||
showConfirmationDialog(
|
||||
gettext(
|
||||
"This will generate a new API Key. The old API Key will cease to function immediately."
|
||||
),
|
||||
generate
|
||||
);
|
||||
} else {
|
||||
generate();
|
||||
}
|
||||
};
|
||||
|
||||
self.deleteApikey = function() {
|
||||
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() {
|
||||
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) {
|
||||
self.updateSettings = function (username, settings) {
|
||||
return OctoPrint.access.users.saveSettings(username, settings);
|
||||
};
|
||||
|
||||
self.saveEnabled = function() {
|
||||
self.saveEnabled = function () {
|
||||
return !self.passwordMismatch();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onStartup = function () {
|
||||
self.userSettingsDialog = $("#usersettings_dialog");
|
||||
};
|
||||
|
||||
self.onAllBound = function(allViewModels) {
|
||||
self.userSettingsDialog.on('show', function() {
|
||||
self.onAllBound = function (allViewModels) {
|
||||
self.userSettingsDialog.on("show", function () {
|
||||
callViewModels(allViewModels, "onUserSettingsShown");
|
||||
});
|
||||
self.userSettingsDialog.on('hidden', function() {
|
||||
self.userSettingsDialog.on("hidden", function () {
|
||||
callViewModels(allViewModels, "onUserSettingsHidden");
|
||||
});
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
function WizardViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
@@ -13,65 +13,85 @@ $(function() {
|
||||
self.finishing = false;
|
||||
self.wizards = [];
|
||||
|
||||
self.isDialogActive = function() {
|
||||
self.isDialogActive = function () {
|
||||
return self.wizardDialog.is(":visible");
|
||||
};
|
||||
|
||||
self.showDialog = function() {
|
||||
if (!CONFIG_WIZARD || !((CONFIG_FIRST_RUN && !CONFIG_ACCESS_CONTROL_ACTIVE) || self.loginState.isAdmin())) return;
|
||||
self.showDialog = function () {
|
||||
if (
|
||||
!CONFIG_WIZARD ||
|
||||
!(
|
||||
(CONFIG_FIRST_RUN && !CONFIG_ACCESS_CONTROL_ACTIVE) ||
|
||||
self.loginState.isAdmin()
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
self.getWizardDetails()
|
||||
.done(function(response) {
|
||||
callViewModels(self.allViewModels, "onWizardDetails", [response]);
|
||||
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({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
if (!self.isDialogActive()) {
|
||||
self.wizardDialog
|
||||
.modal({
|
||||
minHeight: function () {
|
||||
return Math.max(
|
||||
$.fn.modal.defaults.maxHeight() - 80,
|
||||
250
|
||||
);
|
||||
}
|
||||
})
|
||||
.css({
|
||||
"width": "auto",
|
||||
"margin-left": function () {
|
||||
return -($(this).width() / 2);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
callViewModels(self.allViewModels, "onWizardShow");
|
||||
callViewModels(self.allViewModels, "onWizardShow");
|
||||
|
||||
callViewModels(self.allViewModels, "onBeforeWizardTabChange", [OCTOPRINT_INITIAL_WIZARD, undefined]);
|
||||
callViewModels(self.allViewModels, "onAfterWizardTabChange", [OCTOPRINT_INITIAL_WIZARD]);
|
||||
});
|
||||
callViewModels(self.allViewModels, "onBeforeWizardTabChange", [
|
||||
OCTOPRINT_INITIAL_WIZARD,
|
||||
undefined
|
||||
]);
|
||||
callViewModels(self.allViewModels, "onAfterWizardTabChange", [
|
||||
OCTOPRINT_INITIAL_WIZARD
|
||||
]);
|
||||
});
|
||||
};
|
||||
|
||||
self.closeDialog = function() {
|
||||
self.closeDialog = function () {
|
||||
self.wizardDialog.modal("hide");
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onStartup = function () {
|
||||
self.wizardDialog = $("#wizard_dialog");
|
||||
self.wizardDialog.on('show', function(event) {
|
||||
self.wizardDialog.on("show", function (event) {
|
||||
OctoPrint.coreui.wizardOpen = true;
|
||||
});
|
||||
self.wizardDialog.on('hidden', function(event) {
|
||||
self.wizardDialog.on("hidden", function (event) {
|
||||
OctoPrint.coreui.wizardOpen = false;
|
||||
});
|
||||
|
||||
self.reloadOverlay = $("#reloadui_overlay");
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.onUserLoggedIn = function () {
|
||||
self.showDialog();
|
||||
};
|
||||
|
||||
self.onAllBound = function(allViewModels) {
|
||||
self.onAllBound = function (allViewModels) {
|
||||
self.allViewModels = allViewModels;
|
||||
self.wizardDialog.bootstrapWizard({
|
||||
tabClass: "nav nav-list",
|
||||
nextSelector: ".button-next",
|
||||
previousSelector: ".button-previous",
|
||||
finishSelector: ".button-finish",
|
||||
onTabClick: function() {
|
||||
onTabClick: function () {
|
||||
// we don't allow clicking on the tabs
|
||||
return false;
|
||||
},
|
||||
onTabShow: function(tab, navigation, index) {
|
||||
onTabShow: function (tab, navigation, index) {
|
||||
if (index < 0 || tab.length == 0) {
|
||||
return true;
|
||||
}
|
||||
@@ -80,7 +100,10 @@ $(function() {
|
||||
|
||||
if (index == total) {
|
||||
self.wizardDialog.find(".button-next").hide();
|
||||
self.wizardDialog.find(".button-finish").show().removeClass("disabled");
|
||||
self.wizardDialog
|
||||
.find(".button-finish")
|
||||
.show()
|
||||
.removeClass("disabled");
|
||||
} else {
|
||||
self.wizardDialog.find(".button-finish").hide();
|
||||
self.wizardDialog.find(".button-next").show();
|
||||
@@ -91,13 +114,18 @@ $(function() {
|
||||
callViewModels(allViewModels, "onAfterWizardTabChange", [active]);
|
||||
}
|
||||
},
|
||||
onTabChange: function(tab, navigation, index, nextTabIndex, nextTab) {
|
||||
onTabChange: function (tab, navigation, index, nextTabIndex, nextTab) {
|
||||
var current, next;
|
||||
|
||||
if (index == undefined || index < 0 ||
|
||||
nextTabIndex == undefined || nextTabIndex < 0 ||
|
||||
if (
|
||||
index == undefined ||
|
||||
index < 0 ||
|
||||
nextTabIndex == undefined ||
|
||||
nextTabIndex < 0 ||
|
||||
index == nextTabIndex ||
|
||||
tab.length == 0 || nextTab.length == 0) {
|
||||
tab.length == 0 ||
|
||||
nextTab.length == 0
|
||||
) {
|
||||
// let's ignore that nonsense
|
||||
return;
|
||||
}
|
||||
@@ -107,37 +135,52 @@ $(function() {
|
||||
|
||||
if (current != undefined && next != undefined) {
|
||||
var result = true;
|
||||
callViewModels(allViewModels, "onBeforeWizardTabChange", function(method) {
|
||||
// we want to continue evaluating even if result becomes false
|
||||
result = (method(next, current) !== false) && result;
|
||||
});
|
||||
callViewModels(
|
||||
allViewModels,
|
||||
"onBeforeWizardTabChange",
|
||||
function (method) {
|
||||
// we want to continue evaluating even if result becomes false
|
||||
result = method(next, current) !== false && result;
|
||||
}
|
||||
);
|
||||
|
||||
// also trigger the onWizardTabChange event here which we misnamed and
|
||||
// on which we misordered the parameters on during development but which might
|
||||
// already be used somewhere - log a deprecation warning to console though
|
||||
callViewModels(allViewModels, "onWizardTabChange", function(method, viewModel) {
|
||||
log.warn("View model", viewModel, "is using deprecated callback \"onWizardTabChange\", please change to \"onBeforeWizardTabChange\"");
|
||||
callViewModels(allViewModels, "onWizardTabChange", function (
|
||||
method,
|
||||
viewModel
|
||||
) {
|
||||
log.warn(
|
||||
"View model",
|
||||
viewModel,
|
||||
'is using deprecated callback "onWizardTabChange", please change to "onBeforeWizardTabChange"'
|
||||
);
|
||||
|
||||
// we want to continue evaluating even if result becomes false
|
||||
result = (method(current, next) !== false) && result;
|
||||
result = method(current, next) !== false && result;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
},
|
||||
onFinish: function(tab, navigation, index) {
|
||||
onFinish: function (tab, navigation, index) {
|
||||
var closeDialog = true;
|
||||
callViewModels(allViewModels, "onBeforeWizardFinish", function(method) {
|
||||
callViewModels(allViewModels, "onBeforeWizardFinish", function (
|
||||
method
|
||||
) {
|
||||
// we don't need to call all methods here, one method saying that
|
||||
// the dialog must not be closed yet is enough to stop
|
||||
//
|
||||
// we evaluate closeDialog first to make sure we don't call
|
||||
// the method once it becomes false
|
||||
closeDialog = closeDialog && (method() !== false);
|
||||
closeDialog = closeDialog && method() !== false;
|
||||
});
|
||||
|
||||
if (closeDialog) {
|
||||
var reload = false;
|
||||
callViewModels(allViewModels, "onWizardFinish", function(method) {
|
||||
callViewModels(allViewModels, "onWizardFinish", function (
|
||||
method
|
||||
) {
|
||||
// if any of our methods returns that it wants to reload
|
||||
// we'll need to set reload to true
|
||||
//
|
||||
@@ -145,56 +188,62 @@ $(function() {
|
||||
// first, or it won't happen after the reload flag has been
|
||||
// set once due to the || making further evaluation unnecessary
|
||||
// then
|
||||
reload = (method() == "reload") || reload;
|
||||
reload = method() == "reload" || reload;
|
||||
});
|
||||
self.finishWizard().done(function () {
|
||||
self.closeDialog();
|
||||
if (reload) {
|
||||
self.reloadOverlay.show();
|
||||
}
|
||||
callViewModels(allViewModels, "onAfterWizardFinish");
|
||||
});
|
||||
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.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() {
|
||||
self.finishWizard = function () {
|
||||
var deferred = $.Deferred();
|
||||
self.finishing = true;
|
||||
|
||||
self.settingsViewModel.saveData()
|
||||
.done(function() {
|
||||
OctoPrint.wizard.finish(self.wizards)
|
||||
.done(function() {
|
||||
self.settingsViewModel
|
||||
.saveData()
|
||||
.done(function () {
|
||||
OctoPrint.wizard
|
||||
.finish(self.wizards)
|
||||
.done(function () {
|
||||
deferred.resolve(arguments);
|
||||
})
|
||||
.fail(function() {
|
||||
.fail(function () {
|
||||
deferred.reject(arguments);
|
||||
})
|
||||
.always(function() {
|
||||
.always(function () {
|
||||
self.finishing = false;
|
||||
});
|
||||
})
|
||||
.fail(function() {
|
||||
.fail(function () {
|
||||
deferred.reject(arguments);
|
||||
});
|
||||
|
||||
return deferred;
|
||||
};
|
||||
|
||||
self.onSettingsPreventRefresh = function() {
|
||||
self.onSettingsPreventRefresh = function () {
|
||||
return self.isDialogActive();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
* web application.
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
$(function () {
|
||||
var OctoPrint = window.OctoPrint;
|
||||
|
||||
OctoPrint.loginui = {
|
||||
startedUp: false
|
||||
}
|
||||
};
|
||||
|
||||
var overlayElement = $("#login-overlay");
|
||||
var errorElement = $("#login-error");
|
||||
@@ -16,7 +16,7 @@ $(function() {
|
||||
var buttonElement = $("#login-button");
|
||||
var reconnectElement = $("#login-reconnect");
|
||||
|
||||
buttonElement.click(function() {
|
||||
buttonElement.click(function () {
|
||||
var usernameElement = $("#login-user");
|
||||
var passwordElement = $("#login-password");
|
||||
var rememberElement = $("#login-remember");
|
||||
@@ -28,11 +28,12 @@ $(function() {
|
||||
overlayElement.addClass("in");
|
||||
errorElement.removeClass("in");
|
||||
|
||||
OctoPrint.browser.login(username, password, remember)
|
||||
.done(function() {
|
||||
OctoPrint.browser
|
||||
.login(username, password, remember)
|
||||
.done(function () {
|
||||
window.location.href = REDIRECT_URL;
|
||||
})
|
||||
.fail(function() {
|
||||
.fail(function () {
|
||||
usernameElement.val("");
|
||||
passwordElement.val("");
|
||||
|
||||
@@ -45,17 +46,17 @@ $(function() {
|
||||
|
||||
OctoPrint.options.baseurl = BASE_URL;
|
||||
|
||||
OctoPrint.socket.onConnected = function() {
|
||||
OctoPrint.socket.onConnected = function () {
|
||||
buttonElement.prop("disabled", false);
|
||||
offlineElement.removeClass("in");
|
||||
};
|
||||
|
||||
OctoPrint.socket.onDisconnected = function() {
|
||||
OctoPrint.socket.onDisconnected = function () {
|
||||
buttonElement.prop("disabled", true);
|
||||
offlineElement.addClass("in");
|
||||
};
|
||||
|
||||
reconnectElement.click(function() {
|
||||
reconnectElement.click(function () {
|
||||
OctoPrint.socket.reconnect();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
$(function() {
|
||||
$(function () {
|
||||
//~~ OctoPrint client setup
|
||||
|
||||
var OctoPrint = window.OctoPrint;
|
||||
@@ -15,13 +15,18 @@ $(function() {
|
||||
|
||||
var catalog = window["BABEL_TO_LOAD_EN"];
|
||||
if (catalog === undefined) {
|
||||
catalog = {messages: undefined, plural_expr: undefined, locale: undefined, domain: undefined}
|
||||
catalog = {
|
||||
messages: undefined,
|
||||
plural_expr: undefined,
|
||||
locale: undefined,
|
||||
domain: undefined
|
||||
};
|
||||
}
|
||||
babel.Translations.load(catalog).install();
|
||||
|
||||
//~~ Lodash setup
|
||||
|
||||
_.mixin({"sprintf": sprintf, "vsprintf": vsprintf});
|
||||
_.mixin({sprintf: sprintf, vsprintf: vsprintf});
|
||||
|
||||
//~~ View Model
|
||||
|
||||
@@ -52,80 +57,78 @@ $(function() {
|
||||
self.workLoglines = ko.observableArray([]);
|
||||
self.workTitle = ko.observable("");
|
||||
|
||||
self.request = function() {
|
||||
OctoPrint.browser.passiveLogin()
|
||||
.done(function(resp) {
|
||||
self.username(resp.name);
|
||||
self.permitted(_.includes(resp.needs.role, "admin"));
|
||||
self.known(true);
|
||||
self.request = function () {
|
||||
OctoPrint.browser.passiveLogin().done(function (resp) {
|
||||
self.username(resp.name);
|
||||
self.permitted(_.includes(resp.needs.role, "admin"));
|
||||
self.known(true);
|
||||
|
||||
OctoPrint.socket.sendAuth(resp.name, resp.session);
|
||||
});
|
||||
OctoPrint.socket.sendAuth(resp.name, resp.session);
|
||||
});
|
||||
|
||||
OctoPrint.system.getCommandsForSource("core")
|
||||
.done(function(resp) {
|
||||
self.systemCommands(resp);
|
||||
});
|
||||
OctoPrint.system.getCommandsForSource("core").done(function (resp) {
|
||||
self.systemCommands(resp);
|
||||
});
|
||||
|
||||
OctoPrint.printer.getFullState()
|
||||
.done(function(resp) {
|
||||
OctoPrint.printer
|
||||
.getFullState()
|
||||
.done(function (resp) {
|
||||
self.printerConnected(true);
|
||||
self.jobInProgress(resp.state.flags.printing);
|
||||
})
|
||||
.fail(function(xhr) {
|
||||
.fail(function (xhr) {
|
||||
self.printerConnected(false);
|
||||
self.jobInProgress(false);
|
||||
});
|
||||
|
||||
if (OctoPrint.plugins.backup) {
|
||||
OctoPrint.plugins.backup.get()
|
||||
.done(function(resp) {
|
||||
self.backupSupported(true);
|
||||
self.restoreSupported(resp.restore_supported);
|
||||
OctoPrint.plugins.backup.get().done(function (resp) {
|
||||
self.backupSupported(true);
|
||||
self.restoreSupported(resp.restore_supported);
|
||||
|
||||
var backups = resp.backups;
|
||||
backups.sort(function(a, b) { return b.date - a.date });
|
||||
self.backups(backups);
|
||||
var backups = resp.backups;
|
||||
backups.sort(function (a, b) {
|
||||
return b.date - a.date;
|
||||
});
|
||||
self.backups(backups);
|
||||
});
|
||||
} else {
|
||||
self.backupSupported(false);
|
||||
self.restoreSupported(false);
|
||||
self.backups([]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.executeSystemCommand = function(command) {
|
||||
var process = function() {
|
||||
self.executeSystemCommand = function (command) {
|
||||
var process = function () {
|
||||
OctoPrint.system.executeCommand(command.source, command.action);
|
||||
}
|
||||
};
|
||||
|
||||
if (command.confirm) {
|
||||
showConfirmationDialog({
|
||||
message: command.confirm,
|
||||
onproceed: function() {
|
||||
onproceed: function () {
|
||||
process();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
process();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.cancelPrint = function() {
|
||||
OctoPrint.job.cancel()
|
||||
.done(function() {
|
||||
self.request();
|
||||
});
|
||||
}
|
||||
self.cancelPrint = function () {
|
||||
OctoPrint.job.cancel().done(function () {
|
||||
self.request();
|
||||
});
|
||||
};
|
||||
|
||||
self.disconnectPrinter = function() {
|
||||
OctoPrint.connection.disconnect()
|
||||
.done(function() {
|
||||
self.request();
|
||||
});
|
||||
}
|
||||
self.disconnectPrinter = function () {
|
||||
OctoPrint.connection.disconnect().done(function () {
|
||||
self.request();
|
||||
});
|
||||
};
|
||||
|
||||
self.createBackup = function() {
|
||||
self.createBackup = function () {
|
||||
self.workInProgress(true);
|
||||
self.workTitle(gettext("Creating backup..."));
|
||||
self.workLoglines.removeAll();
|
||||
@@ -133,117 +136,157 @@ $(function() {
|
||||
|
||||
if (!self.backupSupported()) return;
|
||||
var excluded = self.excludeFromBackup();
|
||||
OctoPrint.plugins.backup.createBackup(excluded)
|
||||
.done(function() {
|
||||
self.excludeFromBackup([]);
|
||||
})
|
||||
}
|
||||
OctoPrint.plugins.backup.createBackup(excluded).done(function () {
|
||||
self.excludeFromBackup([]);
|
||||
});
|
||||
};
|
||||
|
||||
self.restoreBackup = function(backup) {
|
||||
self.restoreBackup = function (backup) {
|
||||
if (!self.restoreSupported()) return;
|
||||
|
||||
var perform = function() {
|
||||
var perform = function () {
|
||||
self.workInProgress(true);
|
||||
self.workTitle(gettext("Restoring backup..."));
|
||||
self.workLoglines.removeAll();
|
||||
self.workLoglines.push({line: "Preparing to restore...", stream: "message"});
|
||||
self.workLoglines.push({
|
||||
line: "Preparing to restore...",
|
||||
stream: "message"
|
||||
});
|
||||
self.workLoglines.push({line: " ", stream: "message"});
|
||||
self.workDialog.modal({keyboard: false, backdrop: "static", show: true});
|
||||
|
||||
OctoPrint.plugins.backup.restoreBackup(backup);
|
||||
};
|
||||
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(backup.name)}),
|
||||
perform);
|
||||
}
|
||||
showConfirmationDialog(
|
||||
_.sprintf(
|
||||
gettext(
|
||||
'You are about to restore the backup file "%(name)s". This cannot be undone.'
|
||||
),
|
||||
{name: _.escape(backup.name)}
|
||||
),
|
||||
perform
|
||||
);
|
||||
};
|
||||
|
||||
self.logout = function() {
|
||||
OctoPrint.browser.logout()
|
||||
.done(function() {
|
||||
window.location.href = LOGIN_URL;
|
||||
})
|
||||
}
|
||||
self.logout = function () {
|
||||
OctoPrint.browser.logout().done(function () {
|
||||
window.location.href = LOGIN_URL;
|
||||
});
|
||||
};
|
||||
|
||||
self.reconnect = function() {
|
||||
self.reconnect = function () {
|
||||
OctoPrint.socket.reconnect();
|
||||
}
|
||||
};
|
||||
|
||||
self.onSocketConnected = function() {
|
||||
self.onSocketConnected = function () {
|
||||
self.connected(true);
|
||||
self.request();
|
||||
}
|
||||
};
|
||||
|
||||
self.onSocketDisconnected = function() {
|
||||
self.onSocketDisconnected = function () {
|
||||
self.connected(false);
|
||||
}
|
||||
};
|
||||
|
||||
self.onSocketMessage = function(event, data) {
|
||||
self.onSocketMessage = function (event, data) {
|
||||
console.log("onSocketMessage", event, data);
|
||||
if (event === "plugin" && data.plugin === "backup") {
|
||||
switch (data.data.type) {
|
||||
case "logline": {
|
||||
self.workLoglines.push(self._preprocessLine({line: data.data.line, stream: data.data.stream}));
|
||||
self.workLoglines.push(
|
||||
self._preprocessLine({
|
||||
line: data.data.line,
|
||||
stream: data.data.stream
|
||||
})
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "backup_started": {
|
||||
self.workLoglines.push({line: gettext("Creating backup..."), stream: "message"});
|
||||
self.workLoglines.push({
|
||||
line: gettext("Creating backup..."),
|
||||
stream: "message"
|
||||
});
|
||||
self.workLoglines.push({line: " ", stream: "message"});
|
||||
break;
|
||||
}
|
||||
case "backup_failed": {
|
||||
self.workLoglines.push({line: " ", stream: "message"});
|
||||
self.workLoglines.push({line: gettext("Backup creation failed! Check octoprint.log for reasons as to why."), stream: "error"});
|
||||
self.workLoglines.push({
|
||||
line: gettext(
|
||||
"Backup creation failed! Check octoprint.log for reasons as to why."
|
||||
),
|
||||
stream: "error"
|
||||
});
|
||||
self.workInProgress(false);
|
||||
self.request();
|
||||
break;
|
||||
}
|
||||
case "backup_done": {
|
||||
self.workLoglines.push({line: " ", stream: "message"});
|
||||
self.workLoglines.push({line: gettext("Backup created successfully!"), stream: "message"});
|
||||
self.workLoglines.push({
|
||||
line: gettext("Backup created successfully!"),
|
||||
stream: "message"
|
||||
});
|
||||
self.workInProgress(false);
|
||||
self.request();
|
||||
break;
|
||||
}
|
||||
case "restore_started": {
|
||||
self.workLoglines.push({line: gettext("Restoring from backup..."), stream: "message"});
|
||||
self.workLoglines.push({
|
||||
line: gettext("Restoring from backup..."),
|
||||
stream: "message"
|
||||
});
|
||||
self.workLoglines.push({line: " ", stream: "message"});
|
||||
break;
|
||||
}
|
||||
case "restore_failed": {
|
||||
self.workLoglines.push({line: " ", stream: "message"});
|
||||
self.workLoglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"});
|
||||
self.workLoglines.push({
|
||||
line: gettext(
|
||||
"Restore failed! Check the above output and octoprint.log for reasons as to why."
|
||||
),
|
||||
stream: "error"
|
||||
});
|
||||
self.workInProgress(false);
|
||||
break;
|
||||
}
|
||||
case "restore_done": {
|
||||
self.workLoglines.push({line: " ", stream: "message"});
|
||||
self.workLoglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"});
|
||||
self.workLoglines.push({
|
||||
line: gettext(
|
||||
"Restore successful! The server will now be restarted!"
|
||||
),
|
||||
stream: "message"
|
||||
});
|
||||
self.workInProgress(false);
|
||||
break;
|
||||
}
|
||||
case "installing_plugin": {
|
||||
self.workLoglines.push({line: " ", stream: "message"});
|
||||
self.workLoglines.push({
|
||||
line: _.sprintf(gettext("Installing plugin \"%(plugin)s\"..."), {plugin: _.escape(data.data.plugin)}),
|
||||
line: _.sprintf(
|
||||
gettext('Installing plugin "%(plugin)s"...'),
|
||||
{plugin: _.escape(data.data.plugin)}
|
||||
),
|
||||
stream: "message"
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var viewModel = new RecoveryViewModel();
|
||||
|
||||
OctoPrint.socket.onConnected = function() {
|
||||
OctoPrint.socket.onConnected = function () {
|
||||
viewModel.onSocketConnected();
|
||||
};
|
||||
|
||||
OctoPrint.socket.onDisconnected = function() {
|
||||
OctoPrint.socket.onDisconnected = function () {
|
||||
viewModel.onSocketDisconnected();
|
||||
};
|
||||
|
||||
OctoPrint.socket.onMessage("*", function(data) {
|
||||
OctoPrint.socket.onMessage("*", function (data) {
|
||||
viewModel.onSocketMessage(data.event, data.data);
|
||||
});
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
// Accordion
|
||||
// --------------------------------------------------
|
||||
|
||||
|
||||
// Parent container
|
||||
.accordion {
|
||||
margin-bottom: @baseLineHeight;
|
||||
|
||||
+1
-4
@@ -2,14 +2,13 @@
|
||||
// Alerts
|
||||
// --------------------------------------------------
|
||||
|
||||
|
||||
// Base styles
|
||||
// -------------------------
|
||||
|
||||
.alert {
|
||||
padding: 8px 35px 8px 14px;
|
||||
margin-bottom: @baseLineHeight;
|
||||
text-shadow: 0 1px 0 rgba(255,255,255,.5);
|
||||
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
|
||||
background-color: @warningBackground;
|
||||
border: 1px solid @warningBorder;
|
||||
.border-radius(@baseBorderRadius);
|
||||
@@ -31,7 +30,6 @@
|
||||
line-height: @baseLineHeight;
|
||||
}
|
||||
|
||||
|
||||
// Alternate styles
|
||||
// -------------------------
|
||||
|
||||
@@ -62,7 +60,6 @@
|
||||
color: @infoText;
|
||||
}
|
||||
|
||||
|
||||
// Block alerts
|
||||
// -------------------------
|
||||
|
||||
|
||||
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user