Compare commits

..
173 Commits
Author SHA1 Message Date
Gina Häußge 6393de8c7d Preparing release of 1.3.1 2017-01-25 08:24:07 +01:00
Gina Häußge adbd6b7fa1 Preparing release of 1.3.1rc2 2017-01-20 15:33:32 +01:00
Gina Häußge 3da3cfd8a0 Fixed passing of "daemon" legacy parameter on CLI
This time this hopefully really solves #1641
2017-01-20 15:33:24 +01:00
Gina Häußge 4c971a92db from ... import * is only allowed at module level 2017-01-13 14:17:39 +01:00
Gina Häußge 5b3a7bed93 Preparing release of 1.3.1rc1 2017-01-13 13:56:50 +01:00
Gina Häußge 1f0e67f85e Added FAQ link to footer 2017-01-13 13:42:53 +01:00
Noah Martin 74597483dc Added a mask icon for Safari pinned tab and touchbar
(cherry picked from commit ff02192)
2017-01-13 13:33:21 +01:00
Gina Häußge cb89509bb2 Fixed sorting in 3rd party licenses 2017-01-13 13:30:57 +01:00
Gina Häußge c194fdbb28 Added @noahsmartin to AUTHORS 2017-01-13 13:30:38 +01:00
Noah Martin b1057a4cc8 Simplified install process on Mac
(cherry picked from commit 726eec8)
2017-01-13 13:29:11 +01:00
Gina Häußge 20cd13904d Cura: Fix selection of which start/end gcode to choose
So far the plugin selected the gcode script corresponding to the number of
extruders configured in the printer profile. After a close look into the
implementation in Cura itself, prompted by #1708, it turns out that this is
in fact wrong.

Cura selects the gcode script to use based on the maximum of the number of
extruders needed for printing the models in the scene and the minimum number
of extruders needed for generating support (if support extruder is "both" or "first"
or there is only one extruder, that's 1, if it's "second" and there is more than one
extruder, it's 2).

This commit changes the plugin's implementation to mirror this implementation.
The difference to Cura is that we have the number of extruders needed for the
models in the scene hard coded to 1 since we only support STL right now which
can never contain more than one object. If we ever decide to support merging of
multiple STLs into one single multi-extruder print or other model files like AMF
or OBJ from OctoPrint's slicer support, we need to change this.
2017-01-13 12:54:01 +01:00
Gina Häußge 95e4ad82b4 Cura: Fix off-by-one error for placeholder replacement
Affected print_temperature and filament_diameter placeholders.

E.g. `print_temperature2` was wrongly attempting to fetch `print_temperatures[2]`
 instead of `print_temperatures[1]` (0-based-indexing!)

 Partially fixes #1708
2017-01-13 11:25:08 +01:00
Gina Häußge 9e3d2bed65 Merge branch 'improve/passwordManagers' into maintenance 2017-01-12 18:59:39 +01:00
Gina Häußge 7f3d4a8380 Allow configuration of analysis throttling via config.yaml 2017-01-12 18:16:50 +01:00
Gina Häußge e6dd37e26e Various analysis queue fixes
* Fix priority queue sorting (sorts ascending, not descending!)
  * Abort low priority jobs when a high priority job comes in
  * Utilize queue for tracking aborted jobs too
  * Abort analysis for items that are to be deleted/moved (also
    fixes issue under Windows where it was impossible to delete
    a file for which the analysis was still running).
2017-01-12 18:16:42 +01:00
Gina Häußge d69c166f10 Fix unanalysed files from subfolders to not be found on startup 2017-01-12 15:15:02 +01:00
Gina Häußge f6875c0df4 Update german translation 2017-01-12 14:34:00 +01:00
Gina Häußge 3ef7b37dc9 Hide login form when we are already logged in
Otherwise the Lastpass stuff will show up after all, despite
the positioning hack.
2017-01-12 14:23:44 +01:00
Gina Häußge 03085ab39b Fix width/height of login button in navbar 2017-01-12 14:22:34 +01:00
Gina Häußge de0ee08e05 Fix Lastpass input button handling in login form
* move hidden login form to the left to hide overlayed
    Lastpass context buttons
  * do dropdown toggling for login form manually to
    not only ignore clicks into form but also into overlayed
    Lastpass context buttons for closing the dropdown again;
    do close dropdown for included a and button elements
    though
2017-01-12 13:32:10 +01:00
Gina Häußge 881d3bb212 Merge branch 'maintenance' into main/supportPasswordManagers 2017-01-11 19:03:31 +01:00
Gina Häußge fb5d5682e6 Do not eat 0% progress
Fixes #1344 (this time for good I hope)
2017-01-11 17:57:45 +01:00
Gina Häußge 071c32fff1 Ported fix of solid layer count from Ultimaker/CuraEngine#140
Fixes #1692
2017-01-11 16:15:43 +01:00
Gina Häußge 7c74594f06 Adjusted Cura profile handling to match latest Cura Legacy version
* Added/changed mappings of profile to engine settings to
    match Cura Legacy mapping:
    * perimeterBeforeInfill: taken from perimeter_before_infill (new,
      fixes #1693)
    * skinSpeed: taken from solidarea_speed (new)
    * raftAirGapLayer0: sum of raft_airgap and raft_airgap_all
    * raftAirGap: taken from raft_airgap_all (new)
    * raftFanSpeed: changed to 0
    * raftSurfaceThickness: taken from raft_surface_thickness (new)
    * raftSurfaceLinewidth & raftSurfaceLineSpacing: taken from
      raft_surface_linewidth (new)
  * Mach3 Gcode Flavor replaces S parameter with P parameter in
    temperature commands within generated GCODE, like in Cura
    Legacy
2017-01-11 14:50:09 +01:00
Gina Häußge d83440d32d Use full path instead of only the file name for busy detection 2017-01-11 13:53:28 +01:00
Gina Häußge c0dff1359b Fix file_in_path for windows environments 2017-01-11 13:51:40 +01:00
Gina Häußge 2ab7fa4d3a Support volume calculate for S3D files 2017-01-11 12:11:16 +01:00
Gina Häußge f20e985d0d profile => slicing_profile & removed filament 0 check
If the slicer returns values for a tool we want it in our analysis
result, even if it's zero. That way the result will be the same as
if we have our own built in gcode analyser take a look at the
file.

(cherry picked from commit 818ae92)
2017-01-11 12:04:13 +01:00
derpicknicker1 58f934e2c1 Fix issue in getting file metadata after slicing
This fixes the issue that there were no informations about filament
usage in metadata after slicing with cura plugin. Trying to call
profile.get_float("filament_diameter") ended in en exception with
message " 'module' object has no attribute 'get_float' ". So i defined
profile before using profile and now it works.
See issue #1685
Also inserted a check to determine if filament usage is > 0 to exclude
tools with no filament usage in metadata.

(cherry picked from commit c9b38bd)
2017-01-11 12:04:02 +01:00
Gina Häußge 06eae381e4 Fixed an error in the dev env setup docs 2017-01-10 19:01:23 +01:00
Gina Häußge 50965d69ce Include info about setting up dev env in CONTRIBUTING.md 2017-01-10 19:00:58 +01:00
Gina Häußge 6e474d9096 Fix model size calculation during GCODE analysis
* Properly handle G0/G1 with no X, Y, Z coordinates in relative mode
    instead of duplicating coordinates - should fix #1675
  * Only take move commands with X, Y, Z coordinates into account for
    model size calculation - this makes our internal GCODE analysis behave
    like the GCODE viewer's analysis and produce the same model size. The
    downside is that extrusions on the origin are no longer taken into account
    for checking if a model is within bounds of the print bed, but that should
    hopefully not produce any issues in the real world.
2017-01-10 12:16:33 +01:00
Gina Häußge 63c588fce9 Update command line examples in README 2017-01-09 17:07:27 +01:00
Gina Häußge f3f60674fc Allow a retraction z hop of 0 in timelapse configuration
See comment by @markwal at
https://github.com/foosel/OctoPrint/pull/1148#pullrequestreview-14802655
2017-01-09 17:00:10 +01:00
Marc Hannappel dc3182c872 Fix folders doesn't get listed when performing a filtering in file section, issue #1667
(cherry picked from commit 8a8b88a)
2017-01-09 16:54:55 +01:00
Gina Häußge 6c9cac0eca Merge branch 'master' into maintenance 2017-01-09 14:10:04 +01:00
Gina Häußge 101471235c Pinning Jinja to <2.9 for now
Variables defined in an outer scope can no longer be set from an inner scope (see
pallets/jinja#641). Regardless of whether that is right or wrong, we can't control if
people are using such constructs in their plugins, which versions of Jinja >= 2.9 would
now break out of the blue, regardless of OctoPrint version. That is unacceptable sadly
and requires pinning for now, until plugin authors have had a chance to adapt
accordingly.

Also see #1697.
2017-01-09 14:09:49 +01:00
Paul de Vries 6cc84a1473 Make the login overlay always 'visible' in the DOM so that password managers can auto-submit their credentials 2016-12-31 13:13:01 +01:00
Paul de Vries ce1344eb0c Remove legacy onKeyUp and ignored autocomplete 2016-12-30 20:56:08 +01:00
Gina Häußge 84e8f8e1ca Fix terminal filter regexes & add filter for wait 2016-12-16 13:01:56 +01:00
Gina Häußge 2669e79778 Change wording of buttons in cancel confirmation
"Cancel" and "Proceed" is misleading.

Closes #1656
2016-12-16 12:31:07 +01:00
Gina Häußge 42e3922053 Don't care about common params on CLI
--basedir, --config, --verbose, --safe may now come before or after
subcommands and should still be evaluated.

For the server commands (legacy, "server" and "daemon"), the same
should now hold true for the related parameters --host, --port, --debug,
--logging, --iknowwhatimdoing and also --pid (for daemon command).

While having the parameters belong to the individual commands and only
there (which is click's basic approach) is way more cleaner, too many people
were running into issues with that strict approach after all.

I just hope the somewhat hackish approach with context injection needed to
get the less strict version to work won't backfire badly in the long run.

See also #1633 and #1657
2016-12-16 12:18:05 +01:00
Gina Häußge e121569e40 Fix BASEDIR & CONFIGFILE eval in init script & param order
Solves #1657
2016-12-16 10:30:56 +01:00
Gina Häußge a735bcc18d Take keyboard control setting into account for possible check
Solves #1660
2016-12-16 10:13:53 +01:00
Gina Häußge 726787e4db Merge branch 'fix-lsb-include' of https://github.com/tullo-x86/OctoPrint into pr/tullo-x86/fix-lsb-include 2016-12-14 16:15:43 +01:00
Daniel Tullemans ce4e04cabf Include LSB above first use in init script 2016-12-13 17:51:37 -06:00
Gina Häußge fcb0e382b5 Fix missing websocket-client dependency for octoprint client
See #1648
2016-12-13 14:55:43 +01:00
Gina Häußge 0560009204 Merge branch 'dev/supportPasswordManagers' into maintenance 2016-12-13 14:43:45 +01:00
Gina Häußge cb9fba73a2 Move cancel confirmation checkbox up a bit 2016-12-13 14:28:44 +01:00
Gina Häußge cbbfb4af20 Merge branch 'dev/cancelconfirm' of https://github.com/ntoff/OctoPrint into pr/ntoff/dev/cancelconfirm 2016-12-13 14:03:26 +01:00
Gina Häußge 50e55ed30d Do not have CLI interpret OCTOPRINT_VERSION env var
--version is a flag, not an actual parameter (wouldn't really make sense
too). I'm not sure why that isn't the default behaviour of the built-in
version_option decorator tbh.

See #1647
2016-12-12 10:59:22 +01:00
Gina Häußge d0ff9cb65e Fix octoprint --daemon backwards compatibility 2016-12-12 10:05:11 +01:00
ntoff e458e3dd18 cancel confirmation option
display or not the confirmation to cancel a print
2016-12-11 00:52:47 +10:00
Gina Häußge 6773ae221d Gracefully handle suddenly vanished files in storage listing 2016-12-09 14:34:40 +01:00
Gina Häußge ccbf71a96a Fix file that starts with same name as a folder being perceived as in folder
Solves #1637
2016-12-09 13:40:06 +01:00
Gina Häußge 102727b122 [Docs] Fix missing docs for recursive parameter on file API
Solves #1634
2016-12-09 10:50:53 +01:00
Gina Häußge d1f7d39ca9 Embarrassing mistake in .de translation :) 2nd try 2016-12-09 10:49:52 +01:00
Gina Häußge 81d426e5dd Merge branch 'devel' into maintenance
# Conflicts:
#	translations/de/LC_MESSAGES/messages.po
2016-12-09 10:16:57 +01:00
Gina Häußge 0e1f074634 Embarrassing mistake in .de translation :) 2016-12-08 17:11:16 +01:00
Gina Häußge 3b2b262420 Merge branch 'maintenance' into devel 2016-12-08 14:05:05 +01:00
Gina Häußge 3caac586fc Upped version numbers for branches 2016-12-08 14:04:28 +01:00
Gina Häußge 7f5d03d054 Preparing release of 1.3.0 2016-12-08 09:25:13 +01:00
Gina Häußge 558a8957f9 Fix docs for OctoPrint.upload method 2016-12-07 10:59:16 +01:00
Gina Häußge 8d2681ae3f Make OctoPrint.upload's url behave like others
So far only was interpreted relatively to the defined base url.
We want this to behave like other requests from the client lib
though, so now it does.
2016-12-07 10:54:20 +01:00
Gina Häußge 0de6718af3 Fix filesize not being defined 2016-12-07 10:53:48 +01:00
Paul de Vries 6d158cb0d0 Fix small bug on unreliable submit event + seperate onKeyUp event 2016-12-05 15:34:48 +01:00
Paul de Vries e52fbf061d Add support to save credentials to a password manager #1607 2016-12-05 13:56:19 +01:00
Gina Häußge 229f3a2744 Preparing release of 1.3.0rc3 2016-12-02 12:39:28 +01:00
Gina Häußge c00b3de40c Fix temperature history on server reconnect
Two problems solved:

  * Make sure to only process temperature data once we
    have printer profile information on hand to evaluate
    the heater data. If we don't have that yet, create a client
    side backlog and process that once we have the necessary
    data on hand.
  * Do not use uninitialized history cutoff values - if our cutoff
    value hasn't yet synced (no settings response arrived yet),
    just don't perform the cutoff.
2016-12-02 11:06:01 +01:00
Gina Häußge 3d3c93c67d Fix yet another settings caching issue
That api endpoint really is a tough nut. ETag calculation now also
takes full settings dump from settings plugins into account, because
those might be providing custom keys through custom on_settings_load
implementations, for which we will not notice any changes if we are
only looking at the effective config.

Of course, the more we put into that ETag calculation, the slower it will
be and the less sense it will make. Somewhat annoying :/
2016-12-01 13:47:41 +01:00
Gina Häußge 1e84f2ee6e Fix handling of new structures in getOnlyChangedData
Not testing if oldRoot was actually set and contained the
key in question could cause issues if a completely new data
structure was sent to the backend that was not mirrored by
the default settings. Things like e.g. complex configuration
items in a by default empty object.
2016-12-01 13:46:20 +01:00
Gina Häußge 4541148aa5 Merge branch 'maintenance' into devel
# Conflicts:
#	CHANGELOG.md
2016-11-30 14:34:21 +01:00
Gina Häußge e8a4750379 Improved (manually to run) doc test for latest release selector 2016-11-30 14:33:36 +01:00
Gina Häußge 1d0657a8eb Preparing release of 1.2.18 2016-11-30 11:24:50 +01:00
Gina Häußge 65377b396f Added note that jquery and lodash are dependencies of the js client lib 2016-11-28 11:29:17 +01:00
Gina Häußge a66e6b603f Make sure our command line calls always exit
sarge's "wait_events" is unreliable. If an asynchronous
job is started but stops immediately and raises a sarge
Exception (inside the async thread), the associated
command's event will never be set event though the
process finished. So we'd wait indefinitely here.

We circumvent this by first waiting until the commands
are parsed and processed (p.commands contains
elements), then until said commands are started and then
making sure the command's process is actually set. Only
then do we actually have a background process running
that we'll be able to monitor further down, otherwise
the command immediately failed.
2016-11-25 15:45:43 +01:00
Gina Häußge 528e99898f Better error and subprocess handling
Removed a potential deadlock, added logging for all
raised exceptions, made _to_error more solid and
removed another potential encoding issue when
creating diffs
2016-11-25 14:58:09 +01:00
Gina Häußge 8beedce98f Slight rewording in Cura wizard 2016-11-24 12:56:00 +01:00
Gina Häußge 69412d0b8b Preparing release of 1.3.0rc2 part 2 2016-11-24 12:20:29 +01:00
Gina Häußge 23744cdba9 onWizardTabChange => onBeforeWizardTabChange 2016-11-24 11:56:37 +01:00
Gina Häußge 0f53c1aaa6 Pin tornado dependency to 4.0.2 for now
">=4.0.2,<4.1" will pull in 4.1b and we don't want that due to issue with
that and websocket communication due to permessage-deflate.

While we desperately need to migrate to a newer tornado, due to some
voodoo needed to get large streamed uploads and downloads to work
that is probably not completely straightforward and therefore
something for post-1.3.0-stable release.
2016-11-24 11:45:26 +01:00
Gina Häußge 462ab5aa37 Prevent SWU popup when wizard is open 2016-11-24 11:28:45 +01:00
Gina Häußge 01b221ab30 Prepare release of 1.3.0rc2 2016-11-24 11:08:43 +01:00
Gina Häußge d37a6a9114 Actually add config subcommand to CLI 2016-11-24 10:55:03 +01:00
Gina Häußge 9875617046 SWU: "busy" spinner while checking for updates 2016-11-23 17:52:16 +01:00
Gina Häußge daeb3dbc91 Documentation for last_position, pause_position, cancel_position 2016-11-23 17:41:58 +01:00
Gina Häußge ccf77a5dae Restrict pause_position and cancel_position to relevant GCODE scripts 2016-11-23 17:41:43 +01:00
Gina Häußge 6cc3846512 Add M600 (filament change) to long running commands 2016-11-23 15:53:05 +01:00
Gina Häußge 4ed0ed5f99 Fix working dialog of pgmr and swu being closeable while active
Only the close button should work now
2016-11-23 15:11:35 +01:00
Gina Häußge 5c39e9a8a3 Demote pip upgrade message from stderr to stdout in client output
Having that output stay on stderr and hence in shiny red looks way
too alarming considering that it's only a pip update that is not THAT
critical usually (and we don't want to do it automatically anyhow
considering how often that appears to break stuff).
2016-11-23 14:28:50 +01:00
Gina Häußge 5b910b557e Fixed a rare race condition causing a "settings changed" popup in case of local changes
If the SettingsUpdated event for whatever reason got slightly delayed and arrived AFTER
the save request was already processed, in rare situations it could happen that the
"Settings Changed" popup was triggered even though the settings had already been
successfully saved.

Modified such that we now keep track of if we already saw the SettingsUpdated event
associated with our save request and if not we ignore the next one.

To ensure that we don't get out of sync due to that when a settings update request is
sent, but no settings are actually change, we also now always trigger the SettingsUpdated
event, even in such cases. Clients can use the hashs in the payload to test if something
 actually changed - if necessary.
2016-11-23 11:34:58 +01:00
Gina Häußge 4a0d91315c Fix update of webcam streamURL not being recognized
We used to track our webcam stream URL by the global variable
CONFIG_WEBCAMURL. That's still a left over from the architecture
about four years ago and completely obsolete these days.

Additionally it causes issues now that anything rendered into
the page (as this variable value is through initscript.jinja2)
will not be changed unless the page cache is refreshed.

Taking the stream URL from the settings view model instead
solves that problem and is way cleaner anyhow.
2016-11-22 16:17:00 +01:00
donovan6000 1b9bfc6d04 Inapplicable pip arguments can be blacklisted when installing or uninstalling a package 2016-11-22 14:58:39 +01:00
Gina Häußge def5fd4ad3 Changed help text slightly 2016-11-22 14:44:17 +01:00
Gina Häußge 9ed5e37fc8 Reduced code duplication as suggested 2016-11-22 14:00:08 +01:00
Gina Häußge 5424d42b60 Merge branch 'feature/timelapse_repeat_frames' of https://github.com/dattas/OctoPrint into pr/dattas/feature/timelapse_repeat_frames 2016-11-22 13:53:51 +01:00
Gina Häußge 8ff1834442 Merge branch 'maintenance' into devel
# Conflicts:
#	CHANGELOG.md
#	src/octoprint/translations/de/LC_MESSAGES/messages.mo
#	src/octoprint/translations/de/LC_MESSAGES/messages.po
#	translations/de/LC_MESSAGES/messages.mo
#	translations/de/LC_MESSAGES/messages.po
#	translations/messages.pot
2016-11-22 13:49:19 +01:00
Gina Häußge ec04364b47 Preparing release of 1.2.18rc1 2016-11-22 12:47:29 +01:00
Gina Häußge 2fc3819afd Another update of the german translation 2016-11-21 17:43:20 +01:00
Gina Häußge a24beb25a3 _snippets => snippets - because babel ignores folders starting with _ 2016-11-21 17:43:04 +01:00
Gina Häußge 07bbbff038 Fix error border after successfull install of plugin archive
Was caused by incorrectly resetting the uploadFilename.
2016-11-21 16:25:53 +01:00
Gina Häußge c9c2946db2 Allow closing of all pmgr notifications & remove on server disconnect 2016-11-21 16:14:09 +01:00
Gina Häußge 8034a4bb98 Merge branch 'maintenance' into devel 2016-11-21 14:39:24 +01:00
Gina Häußge a88cd9fcfc Copy settings in on_settings_load so we don't mutate them 2016-11-21 13:44:26 +01:00
Gina Häußge 59e4394cdd Allow type specific default values for restricted settings
See #1567
2016-11-21 13:43:53 +01:00
Gina Häußge d991eab87e Only insert divider in system menu if there are custom commands 2016-11-18 15:01:53 +01:00
Gina Häußge 71581c9c93 Fix deletion of migrated system commands
We need to process the deletion in reverse order, or we'll
delete the wrong (or no) commands due to the changing
list size.
2016-11-18 14:54:02 +01:00
Gina Häußge 7489d2da80 Updated german translation 2016-11-18 14:07:51 +01:00
Gina Häußge 7c1bb5c115 Cache templates per locale, otherwise we might get a language mix 2016-11-18 14:07:31 +01:00
Gina Häußge b8278b6a93 Don't safe config.yaml when migrating settings overlays 2016-11-18 13:40:25 +01:00
Gina Häußge 7709150a2b Make backup of config before system command migration 2016-11-18 13:39:31 +01:00
Gina Häußge fc06c91ae8 Auto-migrate manual server system commands in config
If there are custom system menu entries for restart, reboot and/or
shutdown, they are deleted. If the corresponding server command is
not yet configured, the command from the system menu entry is
transfered.
2016-11-18 13:07:19 +01:00
Gina Häußge 2564820d16 Fix ordering of core system commands & slight rewording 2016-11-18 13:05:26 +01:00
Gina Häußge f83625acba New "octoprint config" CLI
Allows getting and setting settings values
2016-11-18 13:04:59 +01:00
Gina Häußge 97bf331307 Add safe mode that disables all third party plugins
Can be enabled either through new --safe command line
parameter or through server.startOnceInSafeMode in
config.yaml

When running in safe mode the plugin manager will
only allow to disable or uninstall third party plugins. Enabling
third party plugins or installing new plugins is disabled.

That will hopefully allow for more straightforward recovery
in case of a misbehaving plugin.
2016-11-18 13:02:16 +01:00
Gina Häußge e4d34f4130 Fix logging during settings initialization
We record the messages logged during that time to a recording
log handler, then playback anything we caught after startup.
2016-11-18 10:25:24 +01:00
Gina Häußge b68ee4df98 If l10n is set on page load, set OctoPrint.options.locale to its value
That way API requests will be made with the locale the page was requested
in.

See #1593
2016-11-18 07:56:56 +01:00
Gina Häußge 0d13c3b439 Add OctoPrint.options.locale and if set send X-Locale header on requests
See #1593
2016-11-18 07:56:49 +01:00
Gina Häußge 1a75dcd5ee Allow locale definition via request header
Important for session less API calls that might return
localized content (e.g. the system commands).

See #1593
2016-11-18 07:56:35 +01:00
Gina Häußge d1cb8ca98a Fix premature parse stop on M114 and M115 response with ok-prefix 2016-11-17 17:30:10 +01:00
Gina Häußge f1a1b851ee Better resilience against exceptions in view models in callViewModels 2016-11-17 17:15:28 +01:00
Gina Häußge 07382d3918 Add (optional) firmware auto detection
If enabled (which it is by default), OctoPrint will now send
an M115 to the printer on initial connection in order to try
to figure out what kind of firmware it is. For FIRMWARE_NAME
values containing "repetier" (case insensitive), all Repetier-
specific flags will be set on the comm layer. For FIRMWARE_NAME
values containing "reprapfirmware", all RepRapFirmware-
specific flags will be set on the comm layer.

For now no other handling will be performed.
2016-11-17 17:13:36 +01:00
Gina Häußge ec12e52865 virtual printer: small fix of temperature responses 2016-11-17 14:46:56 +01:00
Gina Häußge d5a73b8b4f Add chunks util function 2016-11-17 12:14:10 +01:00
Gina Häußge b87348be3b Add support for M115 to virtual printer 2016-11-17 12:13:52 +01:00
Gina Häußge 0ad057cdbb Fix PrintFailed event
Was missing the new fields in the payload
2016-11-16 16:09:42 +01:00
Gina Häußge 1a5f4e0b9f Stop focusing files in list after deleted file
Looks weird, especially with the new yellow highlight.
2016-11-16 16:04:43 +01:00
Gina Häußge f688786fd5 Make cache validation for settings API depend on effective config 2016-11-16 15:38:13 +01:00
Gina Häußge a58b167bed Utilize settings chain maps for plugin default settings too 2016-11-16 15:37:49 +01:00
Gina Häußge 83a08cd927 Fix a small issue with estimator output when no file is selected 2016-11-16 14:12:37 +01:00
Gina Häußge c194cabdcf Fix for select&print not working for SD files anymore
Timing issue, "OctoPrint.job.start()" would be called at a time
when the file had not yet been selected on the server. Hence
a different approach, calculating printerAfterLoading parameter
based on existing information at the time of clicking the
load button and using the print parameter on the select
file API again, as previously.
2016-11-16 14:12:00 +01:00
Gina Häußge 174ffdf06f Simplified a line 2016-11-15 17:26:41 +01:00
Gina Häußge 7ae6240de2 Make CommandLineCaller use unicode instead of bytes
p.(stdout|stderr).text is unicode. p.(stdout|stderr).readline isn't, so decode
manually.

Should hopefully solve #1586 for good now...
2016-11-15 17:26:11 +01:00
Gina Häußge f9253adf72 Remove accidentally commited plugin file 2016-11-15 13:03:18 +01:00
Gina Häußge d52462b9f5 Docs: Fixed GCODE event docs 2016-11-15 11:57:09 +01:00
Gina Häußge cc5f119f1b Include position in PrintPaused and PrintCancelled events
If available. Updated docs accordingly.
2016-11-15 11:56:30 +01:00
Gina Häußge a8ff23abe4 Also track F parameters in G28 commands 2016-11-15 11:55:34 +01:00
Gina Häußge e6c4e0a808 Query byte position on cancel of SD print 2016-11-15 11:55:09 +01:00
Gina Häußge 58835cfd8e Add tracking of cancel position & make public 2016-11-15 11:54:35 +01:00
Gina Häußge e04bdb3571 Allow access to the current printed file position 2016-11-15 10:28:14 +01:00
Gina Häußge 06f7abdb2d Manually track position in file
self._handle.tell lies because of line based reading and
buffering
2016-11-15 10:25:40 +01:00
Gina Häußge 2429ebc1a2 Virtual Printer: Simplified temperature output 2016-11-14 13:45:22 +01:00
Gina Häußge c6b8b1725a Fixed duplicated M140 line (merge error) 2016-11-14 13:26:05 +01:00
Gina Häußge 4a67762ead virtual printer: Track F and flow/feedrate factors 2016-11-14 13:24:56 +01:00
Gina Häußge 0a9475661f SWU: more verbose output on restart fail 2016-11-11 15:26:36 +01:00
Gina Häußge 2c6fb68544 SWU: Fix issue with log output containing non ASCII characters
See #1586
2016-11-11 15:20:19 +01:00
Gina Häußge b4215c885c Support M114 responses without whitespace between coordinates
Because apparently there exist some firmware variants/forks which don't
have spaces between the coordinate entries. Who needs standards :)
2016-11-11 13:24:00 +01:00
Gina Häußge c8273785cd Fix position tracking of virtual printer
Wasn't taking relative moves into account for coordinate persistence.
2016-11-11 11:52:33 +01:00
Gina Häußge 5446dc645c Use default settings preprocessors if none are provided
Re-enables feedback controls.

Closes #1588
2016-11-11 11:45:17 +01:00
Gina Häußge fac83e91f2 Invalidate timelapse cache when config changes 2016-11-09 16:31:43 +01:00
Gina Häußge 153ebc3692 Fixed retractionZHop setting for Z timelapses
Solves issue reported in #1148 for 1.3.0rc1
2016-11-09 16:30:51 +01:00
Gina Häußge b74a5db4d8 Get rid of double scroll bar in printer profile editor 2016-11-09 15:45:39 +01:00
Gina Häußge 47a3e0340e Allow to define a custom bounding box for printer head movements
That bounding box may have larger dimensions than the print volume
(but not smaller ones). That allows to define safe areas for which no
"exceeds print volume" messages need to be triggered.

Solves #1551
2016-11-09 15:45:25 +01:00
Gina Häußge 1c57769af3 Merge branch 'maintenance' into devel 2016-11-08 15:27:33 +01:00
Gina Häußge bc82a18a03 Merge branch 'rc/maintenance' into maintenance 2016-11-08 15:25:05 +01:00
Gina Häußge 6976ac9edd Preparing release of 1.2.17 2016-11-08 11:31:16 +01:00
Gina Häußge d28e0988fb Merge branch 'maintenance' into devel 2016-11-07 16:18:26 +01:00
Gina Häußge 2952b2622e Do not hiccup on ipv6 addresses in the HTTP Host header
Fixed port extraction. Now supports hostname, hostname + port,
ipv4, ipv4 + port, ipv6, ipv6 + port

Fixes #1571
2016-11-07 16:17:16 +01:00
Gina Häußge e847b355cd Fixed an issue with versioneer detecting sdist version
Implicit match on \n appears to be causing issues when
generating the sdist tarball under Windows. Matching against
\s+ instead works reliably. Simply including the newline in the
matched JSON string would also work fine.
2016-11-07 14:24:53 +01:00
Gina Häußge 970880dee6 Added user roles and enabled plugins to settings ETag
Otherwise the cache of /api/settings would not be properly invalidated
on a change in either the user login state or the set of active plugins.

See also #1576
2016-11-07 11:55:26 +01:00
Gina Häußge 4689a405a3 Merge branch 'dev/positionRecordingOnPause' into devel 2016-11-04 12:12:38 +01:00
Gina Häußge fae27c77b5 Have virtual printer coordinates start at 0.0 2016-11-04 12:12:30 +01:00
Gina Häußge 3f0bfa0fc8 New POSITION_UPDATE event for responses to M114 2016-11-04 12:11:16 +01:00
Gina Häußge 35cf623f81 Merge pull request #1550 from dattas/feature/cancel-confirmation
Add confirmation dialog to cancel to prevent accidental cancel of prints
2016-10-26 11:03:40 +02:00
Gina Häußge 7abd35196e Merge pull request #1554 from FHeilmann/FHeilmann-adjust_values_func
Adjust output of values() classmethod to not include function itself
2016-10-26 11:02:12 +02:00
Gina Häußge 21e342ff8a Merge pull request #1561 from donovan6000/devel
Fixed Cura plugin's get_pos_x/y returning the wrong value when self._…
2016-10-26 08:51:32 +02:00
donovan6000 6114ee4f32 Fixed Cura plugin's get_pos_x/y returning the wrong value when self._posX/Y is 0 2016-10-25 22:46:32 -07:00
Florian Heilmann 5ac934bcc4 Fix Typos
Note to self: double and triple check more!

turn "=" into "=="
2016-10-22 12:53:32 +02:00
Florian Heilmann fd1016695f Adjust output of values() classmethod
The way it was before, the function would also return itself. This isn't really a problem here, but if someone takes this function as a guide (like me) they can run into problems when iterating over the returned array, as it contains an element representing "values()" itself.

Another approach would be make use of the inspect package and replace name="values" with inspect.ismethod(name)
2016-10-22 12:39:16 +02:00
Gina Häußge 728172136a Record position on pause & track F 2016-10-21 20:38:15 +02:00
Gina Häußge d3cc96523e Fix M114 in virtual printer 2016-10-21 20:37:41 +02:00
Dattas Moonchaser 7e2382fed4 Add option to repeat last captured frame instead of capturing new frames for the end of a timelapse. Defaults to current behavior (capturing new frames for the time after). Implements foosel/OctoPrint#1422 2016-10-20 19:06:26 -06:00
Dattas Moonchaser 7fb2745f8f Add confirmation dialog to cancel to prevent accidental cancel of print (which is hard to undo!) 2016-10-19 15:22:15 -06:00
126 changed files with 5536 additions and 2848 deletions

No files matched your search

+6 -6
View File
@@ -16,11 +16,11 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.2.17
# maintenance is currently the branch for preparation of maintenance release 1.3.1
# so are any fix/... and improve/... branches
maintenance 1.2.17 354042b84d488db38ac1917bb69bd164f4e7f750 pep440-dev
fix/.* 1.2.17 354042b84d488db38ac1917bb69bd164f4e7f750 pep440-dev
improve/.* 1.2.17 354042b84d488db38ac1917bb69bd164f4e7f750 pep440-dev
maintenance 1.3.1 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
fix/.* 1.3.1 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
improve/.* 1.3.1 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
.* 1.3.0 198d3450d94be1a2 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
+1
View File
@@ -74,6 +74,7 @@ date of first contribution):
* [Mathias Rangel Wulff](https://github.com/mathiasrw)
* [Clemens Niemeyer](https://github.com/clemniem)
* ["I-am-me"](https://github.com/I-am-me)
* [Noah Martin](https://github.com/noahsmartin)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
+139 -42
View File
@@ -1,8 +1,64 @@
# OctoPrint Changelog
## 1.3.0rc1 (2016-10-19)
## 1.3.1 (2017-01-25)
### New Features
### Note for upgraders
#### Change in stock terminal filter configuration
1.3.1 fixes an issue with the two terminal filters for suppressing temperature and SD status messages and adds a new filter for filtering out firmware `wait` messages. These changes will only be active automatically though for stock terminal filter configurations. If you have customized your terminal filters, you'll need to apply these changes manually under "Settings > Terminal filters":
- Changed "Suppress temperature messages" filter, new regex is `(Send: (N\d+\s+)?M105)|(Recv: ok (B|T\d*):)`
- Changed "Suppress SD status messages" filter, new regex is `(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)`
- New "Suppress wait responses" filter, regex is `Recv: wait`
### Improvements
- [#1607](https://github.com/foosel/OctoPrint/issues/1607) - Way better support for password managers (e.g. browser built-in, 1Password, Lastpass, Dashlane)
- [#1638](https://github.com/foosel/OctoPrint/issues/1638) - Make confirmation dialog when cancelling a print optional.
- [#1656](https://github.com/foosel/OctoPrint/issues/1656) - Make wording of buttons on print cancel dialog less confusing.
- [#1705](https://github.com/foosel/OctoPrint/pull/1705) - Simplified install process on Mac by removing dependency on pyobjc.
- [#1706](https://github.com/foosel/OctoPrint/pull/1706) - Added a mask icon for Safari pinned tab and touchbar.
- Support extraction of filament diameter for volume calculation from GCODE files sliced through Simplify3D.
- Abort low priority jobs in the file analysis queue when a high priority job comes in - should make file analysis and hence time estimates show up faster for newly uploaded files.
- Added a terminal filter for firmware `wait` messages to the stock terminal filters. If you did modify your terminal filter configuration, you might want to add this manually:
- New "Suppress wait responses" filter: `Recv: wait`
### Bug fixes
- [#1344](https://github.com/foosel/OctoPrint/issues/1344) - Fix ProgressBarPlugins to not correctly be triggered for 0% (second try, this time hopefully for good).
- [#1637](https://github.com/foosel/OctoPrint/issues/1637) - Fix issue preventing a folder to be deleted that has a name which is a common prefix of the file currently being printed.
- [#1641](https://github.com/foosel/OctoPrint/issues/1641) - Fix issue with `octoprint --daemon` not working.
- [#1647](https://github.com/foosel/OctoPrint/issues/1647) - Fix issue with `octoprint` command throwing an error if an environment variable `OCTOPRINT_VERSION` was set to its version number.
- [#1648](https://github.com/foosel/OctoPrint/issues/1648) - Added missing `websocket-client` dependency of `octoprint client` to install script.
- [#1653](https://github.com/foosel/OctoPrint/issues/1653) - Fix for an issue with the included init script on the BBB (see also [#1654](https://github.com/foosel/OctoPrint/issues/1654))
- [#1657](https://github.com/foosel/OctoPrint/issues/1657) - Fix init script regarding check for configured `CONFIGFILE` variable.
- [#1657](https://github.com/foosel/OctoPrint/issues/1657) - Don't care about ordering of common parameters (like `--basedir`, `--config`) on CLI.
- [#1660](https://github.com/foosel/OctoPrint/issues/1660) - Do not show hint regarding keyboard controls beneath webcam stream if keyboard control feature is disabled.
- [#1667](https://github.com/foosel/OctoPrint/issues/1667) - Fix for matching folders not getting listed in the results when performing a search in the file list.
- [#1675](https://github.com/foosel/OctoPrint/issues/1675) - Fix model size calculation in GCODE analysis, produced wrong values in some cases. Also adjusted calculation to match implementation in GCODE viewer, now both produce identical results.
- [#1685](https://github.com/foosel/OctoPrint/issues/1685) - Cura Plugin: Fix filament extraction from CuraEngine slicing output
- [#1692](https://github.com/foosel/OctoPrint/issues/1692) - Cura Plugin: Fix solid layer calculation (backport from [Ultimaker/CuraEngine#140](https://github.com/Ultimaker/CuraEngine/issues/140))
- [#1693](https://github.com/foosel/OctoPrint/issues/1693) - Cura Plugin: Support `perimeter_before_infill` profile setting. Additionally added support for `solidarea_speed`, `raft_airgap_all`, `raft_surface_thickness`, `raft_surface_linewidth` profile settings and adjusted mapping for engine settings `raftAirGapLayer0`, `raftFanSpeed`, `raftSurfaceThickness`and `raftSurfaceLinewidth` according to current mapping in Cura Legacy and adjusted Mach3 GCODE flavor to substitute `S` with `P` in temperature commands of generated start code, also like in Cura Legacy.
- [#1697](https://github.com/foosel/OctoPrint/issues/1697) - Pin Jinja to versions <2.9 for now due to a backwards compatibility issue with templates for versions newer than that. Also pushed as a hotfix to 1.3.0 (as 1.3.0post1).
- [#1708](https://github.com/foosel/OctoPrint/issues/1708) - Cura Plugin: Fixed selection of `start.gcode` for sliced file
- Allow a retraction z-hop of 0 in timelapse configuration.
- Fix files in sub folders to not be processed by the initial analysis backlog check during startup of the server.
- Various fixes in the file analysis queue:
- High priority items are now really high priority
- Abort analysis for items that are to be deleted/moved to get around an issue with file access under Windows systems.
- Fix stock terminal filters for suppressing temperature messages and SD status messages to also be able to deal with line number prefixes. If you have added additional terminal filters, you will have to apply this fix manually:
- Changed "Suppress temperature messages" filter: `(Send: (N\d+\s+)?M105)|(Recv: ok (B|T\d*):)`
- Changed "Suppress SD status messages" filter: `(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)`
- Fix issue in german translation.
### More information
- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.0...1.3.1)
- Release Candidates:
- [1.3.1rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.1rc1)
- [1.3.1rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.1rc2)
## 1.3.0 (2016-12-08)
### Features
* You can now create folders in the file list, upload files into said folders and thus better manage your projects' files.
* New wizard dialog for system setups that can also be extended by plugins. Replaces the first run dialog for setting up access control and can also be triggered in other cases than only the first run, e.g. if plugins necessitate user input to function properly. Added wizards to help configuring the following components in OctoPrint on first run: access control, webcam URLs & ffmpeg path, server commands (restart, shutdown, reboot), printer profile. Also extended the bundled Cura plugin to add a wizard for its first setup to adjust path and import a slicing profile, and the bundled Software Update plugin to ask the user for details regarding the OctoPrint update configuration. Also see below.
@@ -13,17 +69,27 @@
* New features within the plugin system:
* Plugins may now give hints in which order various hooks or mixin methods should be called by optionally providing an integer value that will be used for sorting the callbacks prior to execution.
* Plugins may now define configuration overlays to be applied on top of the default configuration but before ``config.yaml``.
* New mixin ``UiPlugin` for plugins that want to provide an alternative web interface delivered by the server.
* New mixin `UiPlugin` for plugins that want to provide an alternative web interface delivered by the server.
* New mixin ``WizardPlugin`` for plugins that want to provide wizard components to OctoPrint's new wizard dialog.
* New hook ``octoprint.cli.commands`` for registering a command with the new OctoPrint CLI
* New hook ``octoprint.comm.protocol.gcode.received`` for receiving messages from the printer
* New hook ``octoprint.printer.factory`` for providing a custom factory to contruct the global ``PrinterInterface`` implementation.
* New ``TemplatePlugin`` template type: ``wizard``
* New Javascript client library for utilizing the server's API, can be reused by `UiPlugin`s.
* OctoPrint will now track the current print head position on pause and cancel and provide it as new template variables ``pause_position``/``cancel_position`` for the relevant GCODE scripts. This will allow more intelligent pause codes that park the print head at a rest position during pause and move it back to the exact position it was before the pause on resume ([Example](https://gist.github.com/foosel/1c09e269b1c0bb7a471c20eef50c8d3e)). Note that this is NOT enabled by default and for now will necessitate adjusting the pause and resume GCODE scripts yourself since position tracking with multiple extruders or when printing from SD is currently not fool proof thanks to firmware limitations regarding reliable tracking of the various ``E`` values and the currently selected tool ``T``. In order to fully implement this feature, the following improvements were also done:
* New ``PositionUpdated`` event when OctoPrint receives a response to an ``M114`` position query.
* Extended ``PrintPaused`` and ``PrintCancelled`` events with position data from ``M114`` position query on print interruption/end.
* Added (optional) firmware auto detection. If enabled (which it is by default), OctoPrint will now send an ``M115`` to the printer on initial connection in order to try to figure out what kind of firmware it is. For FIRMWARE_NAME values containing "repetier" (case insensitive), all Repetier-specific flags will be set on the comm layer. For FIRMWARE_NAME values containing "reprapfirmware" (also case insensitive), all RepRapFirmware-specific flags will be set on the comm layer. For now no other handling will be performed.
* Added safe mode flag ``--safe`` and config setting ``startOnceInSafeMode`` that disables all third party plugins when active. The config setting will automatically be removed from `config.yaml` after the server has started through successfully.
* Added ``octoprint config`` CLI that allows easier manipulation of config.yaml entries from the command line. Example: ``octoprint config set --bool server.startOnceInSafeMode true``
### Improvements
* [#1048](https://github.com/foosel/OctoPrint/issues/1048) - Added "Last print time" to extended file information (see also [#1522](https://github.com/foosel/OctoPrint/pull/1522))
* [#1422](https://github.com/foosel/OctoPrint/issues/1422) - Added option for post roll for timed timelapse to duplicate last frame instead of capturing new frames. That makes for a faster render at the cost of a still frame at the end of the rendered video. See also [#1553](https://github.com/foosel/OctoPrint/pull/1553).
* [#1551](https://github.com/foosel/OctoPrint/issues/1551) - Allow to define a custom bounding box for valid printer head movements in the printer profile, to make print dimension check more flexible.
* [#1583](https://github.com/foosel/OctoPrint/pull/1583) - Strip invalid `pip` arguments from `pip uninstall` commands, if provided by the user as additional pip arguments.
* [#1593](https://github.com/foosel/OctoPrint/issues/1593) - Automatically migrate old manual system commands for restarting OctoPrint and rebooting or shutting down the server to the new system wide configuration settings. Make a backup copy of the old `config.yaml` before doing so in case a manual rollback is required.
* New central configuration option for commands to restart OctoPrint and to restart and shut down the system OctoPrint is running on. This allows plugins (like the Software Update Plugin or the Plugin Manager) and core functionality to perform these common administrative tasks without the user needing to define everything redundantly.
* `pip` helper now adjusts `pip install` parameters corresponding to detected `pip` version:
* Removes `--process-dependency-links` when it's not needed
@@ -53,6 +119,9 @@
* Renamed ``GcodeFilesViewModel`` to ``FilesViewModel`` - plugin authors should accordingly update their dependencies from ``gcodeFilesViewModel`` to ``filesViewModel``. Using the old name still works, but will log a warning and stop working with 1.4.x.
* Make sure ``volume.depth`` for circular beds is forced to ``volume.width`` in printer profiles
* Support for `M116`
* Support ``M114`` responses without whitespace between coordinates (protocol consistency - who needs it?).
* `M600` is now marked as a long running command by default.
* Don't focus files in the file list after deleting a file - made the list too jumpy.
* Cura plugin: "Test" button to check if path to cura engine is valid.
* Cura plugin: Wizard component for configuring the path to the CuraEngine binary and for importing the first slicing profile
* GCODE viewer: Added Layer Up/Down buttons (see also [#1306] (https://github.com/foosel/OctoPrint/pull/1306))
@@ -65,76 +134,91 @@
* Plugin Manager: Track managable vs not managable plugins
* Plugin Manager: Allow hiding plugins from Plugin Manager via ``config.yaml``.
* Plugin Manager: Limit upload dialog for plugin archives to .zip, .tar.gz, .tgz and .tar extensions.
* Plugin Manager: Allow closing of all notifications and close them automatically on detected server disconnect. No need to keep a "Restart needed" message around if a restart is in progress.
* Software Update plugin: More verbose output for logged in administrators. Will now log the update commands and their output similar to the Plugin Manager install and uninstall dialog.
* Software Update plugin: CLI for checking for and applying updates
* Software Update plugin: Wizard component for configuring OctoPrint's update mechanism
* Software Update plugin: "busy" spinner on check buttons while already checking for updates.
* Software Update plugin: Prevent update notification when wizard is open.
* Plugin Manager / Software Update plugin: The "There's a new version of pip" message during plugin installs and software updates is no longer displayed like an error.
* Plugin Manager / Software Update plugin: The "busy" dialog can no longer be closed accidentally.
* Timelapse: Better (& earlier) reporting to the user when something's up with the snapshot URL causing issues with capturing timelapse frames and hence making it impossible to render a timelapse movie on print completion.
* Virtual printer: Usage screen for the ``!!DEBUG`` commands on ``!!DEBUG", ``!!DEBUG:help`` or ``!!DEBUG:?``
* Virtual printer: Usage screen for the ``!!DEBUG`` commands on ``!!DEBUG``, ``!!DEBUG:help`` or ``!!DEBUG:?``
* Updated frontend dependencies (possibly relevant for plugin authors):
* Bootstrap to 2.3.2
* JQuery to 2.2.4
* Lodash to 3.10.1
* SockJS to 1.1.1
* Better error resilience against errors in UI components.
* Various improvements in the GCODE interpreter which performs the GCODE analysis
* Various adjustments towards Python 3 compatibility (still a work in progress though, see also [#1411](https://github.com/foosel/OctoPrint/pull/1411), [#1412](https://github.com/foosel/OctoPrint/pull/1412), [#1413](https://github.com/foosel/OctoPrint/pull/1413), [#1414](https://github.com/foosel/OctoPrint/pull/1414))
* Various code refactorings
* Various small UI improvements
* Various documentation improvements
### Bug Fixes
### Bug fixes
* [#1047](https://github.com/foosel/OctoPrint/issues/1047) - Fixed 90 degree webcam rotation for iOS Safari.
* [#1148](https://github.com/foosel/OctoPrint/issues/1148) - Fixed retraction z hop setting for Z-triggered timelapses. Was not correctly propagated to the backend and hence not taking effect.
* [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Invalidate ``/api/settings`` cache on change of the user's login state (include user roles into ETag calculation).
* [#1586](https://github.com/foosel/OctoPrint/issues/1586) - Fixed incompatibility of update script and command line helper with non-ASCII output from called commands.
* [#1588](https://github.com/foosel/OctoPrint/issues/1588) - Fixed feedback controls again.
* [#1599](https://github.com/foosel/OctoPrint/issues/1599) - Properly handle exceptions that arise within the update script during runtime.
* It's not possible anymore to select files that are not machinecode files (e.g. GCODE) for printing on the file API.
* Changes to a user's personal settings via the UI now propagate across sessions.
* Improved compatibility of webcam rotation CSS across newer browsers (see also [#1436](https://github.com/foosel/OctoPrint/pull/1436))
* Fix for system menu not getting properly reloaded after entries changed
* Invalidate ``/api/settings`` cache on change of the currently enabled plugins (by including plugin names into ETag calculation) and/or on change of the current effective config.
* Fix for `/api/settings` not being properly invalidated for plugin settings that do not have a representation in `config.yaml` but are only added at runtime (and hence are not captured by `config.effective`).
* Invalidate ``/api/timelapse`` cache on change of the current timelapse configuration.
* Fixed an issue causing the version number not to be properly extracted from ``sdist`` tarballs generated under Windows.
* Get rid of double scroll bar in printer profile editor.
* Fixed tracking of current byte position in file being streamed from disk. Turns out that ``self._handle.tell`` lied to us thanks to line buffering.
* Fixed select & print not working anymore for SD files thanks to a timing issue.
* Fixed ``PrintFailed`` event payload (was still missing new folder relevant data).
* Fixed premature parse stop on ``M114`` and ``M115`` responses with ``ok``-prefix.
* Make sure `?l10n` request parameter gets also propagated to API calls as `X-Locale` header in case of locale sensitive API responses.
* Fix language mixture due to cached template configs including localized strings; cache per locale.
* Only insert divider in system menu after core commands if there are custom commands.
* Fix update of webcam stream URL not being applied due to caching.
* Fixed a rare race condition causing the new "The settings changed, reload?" popup to show up even when the settings change originated in the same client instance.
* Fixed a bunch of missing translations.
* Pinned Tornado version to 4.0.2. Former version requirement was able to pull in a beta version causing issues with websockets due to a bug in `permessage-deflate` handling. The Tornado requirement needs an update, but we'll leave it at 4.0.2 for 1.3.0 since we'll need to do some migration work for compatibility with anything newer. Potentially related to [#1523](https://github.com/foosel/OctoPrint/issues/1523).
* Fix a rare race condition in the command line helper and the update script that could cause the code to hang due to waiting on an event that would never be set.
* Fix issue with handling new settings substructures when they are compared to existing settings data in order to find the structural diff.
* Fix for the temperature graph not displaying the data history on site reload.
### Changes from `maintenance` not yet released as part of a stable release
### More information
#### Improvements
* [Commits](https://github.com/foosel/OctoPrint/compare/1.2.18...1.3.0)
* Release Candidates:
* [1.3.0rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc1)
* [1.3.0rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc2)
* [1.3.0rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc3)
* Allow arbitrary frame rates for creating timelapses. Before, the entered fps value was also directly used as frame rate for the actual video, which could cause problems with any frame rates not specified in the MPEG2 standard. Now OctoPrint will use a standard frame rate for the rendered video and render the timelapse stills into the finished movie with the configured frame rate.
* Limit Cura profile importer to `.ini` files and clarified the supported versions
* Add support for the `R` parameter for `M109` and `M190`
#### Bug fixes
* [#1541](https://github.com/foosel/OctoPrint/issues/1541) - Fix selecting the printer profile to use by default
* [#1543](https://github.com/foosel/OctoPrint/issues/1543) - Fix target temperature propagation from communication layer
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.3.0rc1))
## 1.2.17rc4 (2016-10-17)
### Bug fixes
* Properly handle empty JS file list from plugins. Solves a 500 on OctoPrint instances without any third party plugins installed generated during web asset bundling introduced in 1.2.17rc2.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.17rc3...1.2.17rc4))
## 1.2.17rc3 (2016-10-13)
### Bug fixes
* Fixed a wrong order in loading JS files on the client introduced in 1.2.17rc2 to make the UI more resilient against broken plugin JS.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.17rc2...1.2.17rc3))
## 1.2.17rc2 (2016-10-13)
## 1.2.18 (2016-11-30)
### Improvements
* Improved the `serial.log` logging handler to roll over serial log on new connections to the printer instead of continuously appending to the same file. Please note that `serial.log` is a debugging tool only and should *not* be left enabled unless you are trying to troubleshoot something in your printer communication.
* Split JS/CSS/LESS asset bundles according into asset bundles for core + bundled plugins ("packed_core.{js|css|less}") and third party plugins ("packed_plugins.{js|css|less}"). That will allow the core UI to still function properly even if an installed third party plugin produces invalid JS and therefore causes a parser error for the whole plugin JS file. See [#1544](https://github.com/foosel/OctoPrint/issues/1544) for an example of such a situation.
* Allow arbitrary frame rates for creating timelapses. Before, the entered fps value was also directly used as frame rate for the actual video, which could cause problems with any frame rates not specified in the MPEG2 standard. Now OctoPrint will use a standard frame rate for the rendered video and render the timelapse stills into the finished movie with the configured frame rate.
* Limited Cura profile importer to `.ini` files and clarified the supported versions
* Add support for the `R` parameter for `M109` and `M190`
### Bug fixes
* Fixed a bug causing the update of OctoPrint to not work under certain circumstances: If 1.2.16 was installed and the settings were *never* saved via the "Settings" dialog's "Save", the update of OctoPrint would fail due to a `KeyError` in the updater. Reason is a renamed property, properly switched to when saving the settings.
* Fixed the logging subsystem to not properly clean up after itself.
* [#1541](https://github.com/foosel/OctoPrint/issues/1541) - Fix selecting the printer profile to use by default
* [#1543](https://github.com/foosel/OctoPrint/issues/1543) - Fix target temperature propagation from communication layer
* [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Fix issue with restricted settings getting parsed to the wrong data structure in the frontend if loaded anonymously first.
* [#1571](https://github.com/foosel/OctoPrint/issues/1571) - Fix parsing of port number from HTTP Host header for IPv6 addresses
* Fix issue with settings restriction causing internal settings defaults to be changed.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.17rc1...1.2.17rc2))
### More information
## 1.2.17rc1 (2016-10-06)
* [Commits](https://github.com/foosel/OctoPrint/compare/1.2.17...1.2.18)
* Release Candidates:
* [1.2.18rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.18rc1)
## 1.2.17 (2016-11-08)
### Improvements
@@ -142,6 +226,8 @@
* Log full stack trace on socket connection errors when debug logging for `octoprint.server.util.sockjs` is enabled
* ``SettingsPlugin``s may now mark configuration paths as restricted so that they are not returned on the REST API
* Updated LESS.js version
* Improved the `serial.log` logging handler to roll over serial log on new connections to the printer instead of continuously appending to the same file. Please note that `serial.log` is a debugging tool only and should *not* be left enabled unless you are trying to troubleshoot something in your printer communication.
* Split JS/CSS/LESS asset bundles according into asset bundles for core + bundled plugins ("packed_core.{js|css|less}") and third party plugins ("packed_plugins.{js|css|less}"). That will allow the core UI to still function properly even if an installed third party plugin produces invalid JS and therefore causes a parser error for the whole plugin JS file. See [#1544](https://github.com/foosel/OctoPrint/issues/1544) for an example of such a situation.
### Bug fixes
@@ -150,8 +236,19 @@
* Fixed issue causing ``remember_me`` cookie not to be deleted properly on logout
* Fixed broken filter toggling on ``ItemListHelper`` class used for various lists throughout the web interface
* Fixed an issue with the preliminary page never reporting that the server is now up if the page generated during preliminary caching had no cache headers set (e.g. because it contained the first run setup wizard)
* Fixed a bug causing the update of OctoPrint to not work under certain circumstances: If 1.2.16 was installed and the settings were *never* saved via the "Settings" dialog's "Save", the update of OctoPrint would fail due to a `KeyError` in the updater. Reason is a renamed property, properly switched to when saving the settings.
* Fixed the logging subsystem to properly clean up after itself.
* Fixed a wrong order in loading JS files on the client introduced in 1.2.17rc2 to make the UI more resilient against broken plugin JS.
* Properly handle empty JS file list from plugins. Solves a 500 on OctoPrint instances without any third party plugins installed generated during web asset bundling introduced in 1.2.17rc2.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.2.17rc1))
### More information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.2.17)
* Release Candidates:
* [1.2.17rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc1)
* [1.2.17rc2](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc2)
* [1.2.17rc3](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc3)
* [1.2.17rc4](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc4)
## 1.2.16 (2016-09-23)
+7 -1
View File
@@ -12,6 +12,7 @@ or **[creating pull requests](#pull-requests)**.
* [Where can I find which version and branch I'm on?](#where-can-i-find-which-version-and-branch-im-on)
* [Where can I find those log files you keep talking about?](#where-can-i-find-those-log-files-you-keep-talking-about)
* [Where can I find my browser's error console?](#where-can-i-find-my-browsers-error-console)
* [Setting up a development environment](#setting-up-a-development-environment)
* [Pull requests](#pull-requests)
* [What do the branches mean?](#what-do-the-branches-mean)
* [How OctoPrint is versioned](#how-octoprint-is-versioned)
@@ -235,6 +236,10 @@ find information on how to do just that in the
See [How to open the Javascript Console in different browsers](https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers)
## Setting up a development environment
See [the corresponding chapter in the documentation](http://docs.octoprint.org/en/master/development/index.html#setting-up-a-development-environment).
## Pull requests
1. If you want to add a new feature to OctoPrint, **please always first
@@ -315,7 +320,7 @@ There are three main branches in OctoPrint:
add a commit after release to this branch - `<x>.<y>.<z>.post<commits since x.y.z>`
(e.g. `1.2.9.post1`).
* `maintenance`: Improvements and fixes of the current release that make up
the next release go here. More or less continously updated. You can consider
the next release go here. More or less continuously updated. You can consider
this a preview of the next release version. It should be very stable at all
times. Anything you spot in here helps tremendously with getting a rock solid
next stable release, so if you want to help out development, running the
@@ -391,6 +396,7 @@ the local version identifier to allow for an exact determination of the active c
* 2016-09-09: New `rc/*` branches explained.
* 2016-09-23: Some more work on "How to file a bug report" based on recent
experiences
* 2017-01-25: Fixed a typo
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
+4 -4
View File
@@ -86,27 +86,27 @@ following usage examples assume that said `octoprint` script is on your `PATH`.
You can start the server via
octoprint
octoprint serve
By default it binds to all interfaces on port 5000 (so pointing your browser to `http://127.0.0.1:5000`
will do the trick). If you want to change that, use the additional command line parameters `host` and `port`,
which accept the host ip to bind to and the numeric port number respectively. If for example you want the server
to only listen on the local interface on port 8080, the command line would be
octoprint --host=127.0.0.1 --port=8080
octoprint serve --host=127.0.0.1 --port=8080
Alternatively, the host and port on which to bind can be defined via the configuration.
If you want to run OctoPrint as a daemon (only supported on Linux), use
octoprint --daemon {start|stop|restart} [--pid PIDFILE]
octoprint daemon {start|stop|restart} [--pid PIDFILE]
If you do not supply a custom pidfile location via `--pid PIDFILE`, it will be created at `/tmp/octoprint.pid`.
You can also specify the configfile or the base directory (for basing off the `uploads`, `timelapse` and `logs` folders),
e.g.:
octoprint --config /path/to/another/config.yaml --basedir /path/to/my/basedir
octoprint serve --config /path/to/another/config.yaml --basedir /path/to/my/basedir
See `octoprint --help` for further information.
+5 -15
View File
@@ -11,13 +11,10 @@ thanks to everyone who contributed!
* Andrew Moorby
* Arnljot Arntsen
* Aurelio Bernal
* Bart Zudell
* Boris Hussein
* Brad Jackson
* Brad Mooneyham
* Brent Fiegle
* Brian E. Tyler
* Charles Mitchell
* Christopher Day
* Christian Petropolis
* COLLE+McVOY
@@ -26,35 +23,27 @@ thanks to everyone who contributed!
* DeltaMaker 3D Printers
* Doug Johnson
* E3D BigBox
* Erik de Bruijn
* Ernesto Martinez
* Exovite
* Frank Sander
* Gary Deen
* Gary N McKinney
* George Robles
* Gregor Lütolf
* J. Eckert
* Jason Galarneau
* Joe Korzeniewski
* Jamie van Dyke
* Josh Daniels
* Joshua David Gregory
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Korneel Bullens
* Lamin Kivelä
* M Khorakiwala
* Makespace Madrid
* Mark Lane
* Marcus Ackermann
* Mark Qvist
* Mark Walker
* Masayoshi Mitsui
* Michael Aumock
* Michael McDargh Sr
* Miles Flavel
* NateTheApe3DPrints
* Nikolai Langer
* Noe Ruiz
* Patrick McGinnis
* Peter Grace
@@ -66,13 +55,14 @@ thanks to everyone who contributed!
* Samer Najia
* SD3D
* SeeMeCNC
* Shane Ekerbicer
* Simon Hallam
* Stefan Krister
* Stephane Schittly
* Steven Pearson
* Sven Mueller
* Terrance Shaw
* Thomas Hatley
* Timeshell.ca
* Trent Shumay
and 963 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1016 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+1
View File
@@ -32,6 +32,7 @@
## Server
* [appdirs](http://github.com/ActiveState/appdirs): MIT
* [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
* [Click](http://click.pocoo.org/): BSD
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
+2 -2
View File
@@ -286,9 +286,9 @@ Files
- Type
- Description
* - ``hash``
- 1
- 0..1
- String
- MD5 hash of the file
- MD5 hash of the file. Only available for ``local`` files.
* - ``size``
- 0..1
- Number
+149 -2
View File
@@ -16,9 +16,14 @@ Retrieve all files
Retrieve information regarding all files currently available and regarding the disk space still available
locally in the system.
By default only returns the files and folders in the root directory. If the query parameter ``recursive``
is provided and set to ``true``, returns all files and folders.
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
**Example**:
**Example 1**:
Fetch only the files and folders from the root folder.
.. sourcecode:: http
@@ -35,6 +40,10 @@ Retrieve all files
"files": [
{
"name": "whistle_v2.gcode",
"path": "whistle_v2.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "...",
"size": 1468987,
"date": 1378847754,
"origin": "local",
@@ -60,15 +69,140 @@ Retrieve all files
},
{
"name": "whistle_.gco",
"path": "whistle_.gco",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"origin": "sdcard",
"refs": {
"resource": "http://example.com/api/files/sdcard/whistle_.gco"
}
},
{
"name": "folderA",
"path": "folderA",
"type": "folder",
"typePath": ["folder"],
"children": [],
"size": 1334
}
],
"free": "3.2GB"
}
**Example 2**
Recursively fetch all files and folders.
Fetch only the files and folders from the root folder.
.. sourcecode:: http
GET /api/files?recursive=true HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"files": [
{
"name": "whistle_v2.gcode",
"path": "whistle_v2.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "...",
"size": 1468987,
"date": 1378847754,
"origin": "local",
"refs": {
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
"download": "http://example.com/downloads/files/local/whistle_v2.gcode"
},
"gcodeAnalysis": {
"estimatedPrintTime": 1188,
"filament": {
"length": 810,
"volume": 5.36
}
},
"print": {
"failure": 4,
"success": 23,
"last": {
"date": 1387144346,
"success": true
}
}
},
{
"name": "whistle_.gco",
"path": "whistle_.gco",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"origin": "sdcard",
"refs": {
"resource": "http://example.com/api/files/sdcard/whistle_.gco"
}
},
{
"name": "folderA",
"path": "folderA",
"type": "folder",
"typePath": ["folder"],
"children": [
{
"name": "test.gcode",
"path": "folderA/test.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "...",
"size": 1234,
"date": 1378847754,
"origin": "local",
"refs": {
"resource": "http://example.com/api/files/local/folderA/test.gcode",
"download": "http://example.com/downloads/files/local/folderA/test.gcode"
}
},
{
"name": "subfolder",
"path": "folderA/subfolder",
"type": "folder",
"typePath": ["folder"],
"children": [
{
"name": "test.gcode",
"path": "folderA/subfolder/test2.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "...",
"size": 100,
"date": 1378847754,
"origin": "local",
"refs": {
"resource": "http://example.com/api/files/local/folderA/subfolder/test2.gcode",
"download": "http://example.com/downloads/files/local/folderA/subfolder/test2.gcode"
}
},
],
"size": 100,
"refs": {
"resource": "http://example.com/api/files/local/folderA/subfolder",
}
],
"size": 1334,
"refs": {
"resource": "http://example.com/api/files/local/folderA",
}
}
],
"free": "3.2GB"
}
:param recursive: If set to ``true``, return all files and folders recursively. Otherwise only return items on same level.
:statuscode 200: No error
.. _sec-api-fileops-retrievelocation:
@@ -81,6 +215,9 @@ Retrieve files from specific location
Retrieve information regarding the files currently available on the selected `location` and -- if targeting
the ``local`` location -- regarding the disk space still available locally in the system.
By default only returns the files and folders in the root directory. If the query parameter ``recursive``
is provided and set to ``true``, returns all files and folders.
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
**Example**:
@@ -100,6 +237,10 @@ Retrieve files from specific location
"files": [
{
"name": "whistle_v2.gcode",
"path": "whistle_v2.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "...",
"size": 1468987,
"date": 1378847754,
"origin": "local",
@@ -130,6 +271,7 @@ Retrieve files from specific location
:param location: The origin location from which to retrieve the files. Currently only ``local`` and ``sdcard`` are
supported, with ``local`` referring to files stored in OctoPrint's ``uploads`` folder and ``sdcard``
referring to files stored on the printer's SD card (if available).
:param recursive: If set to ``true``, return all files and folders recursively. Otherwise only return items on same level.
:statuscode 200: No error
:statuscode 404: If `location` is neither ``local`` nor ``sdcard``
@@ -196,6 +338,8 @@ Upload file or create folder
"local": {
"name": "whistle_v2.gcode",
"path": "whistle_v2.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"origin": "local",
"refs": {
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
@@ -324,6 +468,9 @@ Retrieve a specific file's or folder's information
If the file is unknown, a :http:statuscode:`404` is returned.
If the targeted path is a folder, by default only its direct children will be returned. If ``recursive`` is
provided and set to ``true``, all sub folders and their children will be returned too.
On success, a :http:statuscode:`200` is returned, with a :ref:`file information item <sec-api-datamodel-files-file>`
as the response body.
@@ -368,7 +515,7 @@ Retrieve a specific file's or folder's information
:param location: The location of the file for which to retrieve the information, either ``local`` or ``sdcard``.
:param filename: The filename of the file for which to retrieve the information
:param children: Whether to include children of folders (true, default) or not (false)
:param recursive: If set to ``true``, return all files and folders recursively. Otherwise only return items on same level.
:statuscode 200: No error
:statuscode 404: If ``target`` is neither ``local`` nor ``sdcard``, ``sdcard`` but SD card support is disabled or the
requested file was not found
+1 -2
View File
@@ -145,7 +145,6 @@ You'll need a user account with administrator privileges.
cd OctoPrint
virtualenv venv
source venv/bin/activate
pip install -U pyobjc
pip install -e .[develop]
You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
@@ -167,7 +166,7 @@ IDE Setup
PyCharm
.......
- "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint``)
- "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
- "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
- Right click "src" in project tree, mark as source folder
+50 -12
View File
@@ -308,6 +308,17 @@ PrintCancelled
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of cancelling, if available
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
* ``position.e``: e coordinate (of currently selected extruder), as reported back from the firmware through `M114`
* ``position.t``: last tool selected *through OctoPrint* (note that if you did change the printer's selected
tool outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will NOT
be accurate)
* ``position.f``: last feedrate for move commands **sent through OctoPrint** (note that if you modified the
feedrate outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will
NOT be accurate)
.. deprecated:: 1.3.0
@@ -324,6 +335,17 @@ PrintPaused
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``position``: the print head position at the time of pausing, if available
* ``position.x``: x coordinate, as reported back from the firmware through `M114`
* ``position.y``: y coordinate, as reported back from the firmware through `M114`
* ``position.z``: z coordinate, as reported back from the firmware through `M114`
* ``position.e``: e coordinate (of currently selected extruder), as reported back from the firmware through `M114`
* ``position.t``: last tool selected *through OctoPrint* (note that if you did change the printer's selected
tool outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will NOT
be accurate)
* ``position.f``: last feedrate for move commands **sent through OctoPrint** (note that if you modified the
feedrate outside of OctoPrint, e.g. through the printer controller, or if you are printing from SD, this will
NOT be accurate)
.. deprecated:: 1.3.0
@@ -352,37 +374,53 @@ GCODE processing
----------------
PowerOn
The GCode has turned on the printer power via M80
An ``M80`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
PowerOff
The GCODE has turned on the printer power via M81
An ``M81`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
Home
The head has gone home via G28
A ``G28`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
ZChange
The printer's Z-Height has changed (new layer)
The printer's Z-Height has changed (new layer) through a ``G0`` or ``G1`` that was sent to the printer through OctoPrint
(not triggered when printing from SD!)
Paused
The print has been paused
Dwell
A ``G4`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
Waiting
The print is paused due to a gcode wait command
One of the following commands was sent to the printer through OctoPrint (not triggered when printing from SD!):
``M0``, ``M1``, ``M226``
Cooling
The GCODE has enabled the platform cooler via M245
An ``M245`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
Alert
The GCODE has issued a user alert (beep) via M300
An ``M300`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
Conveyor
The GCODE has enabled the conveyor belt via M240
An ``M240`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
Eject
The GCODE has enabled the part ejector via M40
An ``M40`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
EStop
The GCODE has issued a panic stop via M112
An ``M112`` was sent to the printer through OctoPrint (not triggered when printing from SD!)
PositionUpdate
The response to an ``M114`` was received by OctoPrint. The payload contains the current position information
parsed from the response and (in the case of the selected tool ``t`` and the current feedrate ``f``) tracked
by OctoPrint.
Payload:
* ``x``: x coordinate, parsed from response
* ``y``: y coordinate, parsed from response
* ``z``: z coordinate, parsed from response
* ``e``: e coordinate, parsed from response
* ``t``: last tool selected *through OctoPrint*
* ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint*
Timelapses
----------
+27
View File
@@ -60,9 +60,36 @@ All GCODE scripts have access to the following template variables through the te
* ``printer_profile``: The currently selected Printer Profile, including
information such as the extruder count, the build volume size, the filament diameter etc.
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!)
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
and ``script.name`` respectively.
There are a couple of additional template variables available for the following specific scripts:
* ``afterPrintPaused`` and ``beforePrintResumed``
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists
of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool
``t`` taken from commands sent through OctoPrint.
* ``afterPrintCancelled``
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
current tool ``t`` taken from commands sent through OctoPrint.
.. warning::
Note that current firmware implementations only report back one ``E`` value, the current extrusion value for the current
extruder. Retrieving all ``E`` values by cycling through all extruders on pause and cancel is something OctoPrint
currently does NOT do since it would simply take too long. That means that if you want to write a ``beforePrintResumed``
script that basically resets everything back to the point when the printer was paused *and* you are running with
multiple extruders, you'll have to find some other way to have your ``E`` values set correctly for all your available
extruders - the data available in ``pause_position`` will *not* suffice. Additionally, most firmwares don't report
the currently selected tool in the ``M114`` response, meaning that the only way OctoPrint can keep track of that is
by tracking it itself. Same goes for the current feed rate ``F``. So if you are printing from SD, this data will be
*wrong*. This is also the reason why OctoPrint currently doesn't bundle a more sophisticated pause and resume script
that would actually move the print head out of the way and pause and back to the original position on resume - it
might cause issues for the multitude of users out there with multi-extruder setups or for people printing from the
printer's SD, thanks to the lack of information the firmware provides.
The :ref:`predefined GCODE scripts <sec-features-gcode_scripts-predefined>` are also called with the following additional
template variables:
+11 -3
View File
@@ -14,6 +14,10 @@
``OctoPrint.options.baseurl``
The base URL of the OctoPrint API
``OctoPrint.options.locale``
The locale to set in ``X-Locale`` headers on API requests. Useful for API
endpoints that might return localized content.
.. js:data:: OctoPrint.plugins
Registration of client library components provided by plugins.
@@ -251,14 +255,18 @@
**Example:**
Uploading a file from a file input element, updating a label with the current upload progress.
Uploading a file to ``some/path`` on the blueprint of plugin ``myplugin``, from a file input element,
updating a label with the current upload progress.
.. code-block:: javascript
var fileInput = $("#my-file-input");
var progressOutput = $("#progress-output");
OctoPrint.upload("/plugins/myplugin/some/path", fileInput, "myfilename.dat", {"somekey": "somevalue"})
OctoPrint.upload(OctoPrint.getBlueprintUrl("myplugin") + "some/path",
fileInput,
"myfilename.dat",
{"somekey": "somevalue"})
.progress(function(data) {
if (data.total) {
var percentage = Math.round(data.loaded * 100 / data.total);
@@ -273,7 +281,7 @@
progressOutput.text("Uploaded!");
});
:param string url: The URL to ``POST`` the upload to
:param string url: URL to which to POST the upload, relative to base url or absolute
:param object file: The file to object, see description for details
:param string filename: An optional file name to use for the upload
:param object additional: An optional object of additional key/value pairs to set on the uploaded form data
+11 -2
View File
@@ -5,7 +5,8 @@ JavaScript Client Library
#########################
The JS Client Library provides an interface to all of OctoPrint's API, including the SockJS based socket to send
push messages from the server to connected clients. It is available as packed web asset file at ``/static/webassets/packed_client.js`` or as individual
push messages from the server to connected clients. It is available as packed web
asset file at ``/static/webassets/packed_client.js`` or as individual
component files at ``/static/js/app/client/<component>.js`` relative to your
OctoPrint instance's base URL (e.g. ``http://octopi.local/static/webassets/packed_client.js``).
@@ -27,10 +28,18 @@ correct URL prefix:
<script type="text/javascript" src="{{ url_for("static", filename="webassets/packed_client.js") }}"></script>
<!--
individual components
individual components (do not forget base!)
-->
<script type="text/javascript" src="{{ url_for("static", filename="js/app/client/<component>.js") }}"></script>
Regardless of which way you use to include the library, you'll also need to make sure you included JQuery and lodash,
because the library depends on those to be available (as ``$`` and ``_``). You can embed those like this:
.. code-block:: html
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
Note that all components depend on the ``base`` component to be present, so if you are only including a select
number of components, make sure to at the very least include that one to be able to utilize the client.
+10 -9
View File
@@ -13,7 +13,7 @@
# /etc/default/octoprint.
### END INIT INFO
# Author: Sami Olmari
# Author: Sami Olmari & Gina Häußge
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="OctoPrint Daemon"
@@ -21,9 +21,14 @@ NAME="OctoPrint"
PKGNAME=octoprint
PIDFILE=/var/run/$PKGNAME.pid
SCRIPTNAME=/etc/init.d/$PKGNAME
DEFAULTS=/etc/default/$PKGNAME
# Read configuration variable file if it is present
[ -r /etc/default/$PKGNAME ] && . /etc/default/$PKGNAME
[ -r $DEFAULTS ] && . $DEFAULTS
# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions
# Exit if the DAEMON is not set
if [ -z "$DAEMON" ]
@@ -38,10 +43,6 @@ fi
# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] && . /etc/default/rcS
# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions
if [ -z "$START" -o "$START" != "yes" ]
then
log_warning_msg "Not starting $PKGNAME, edit /etc/default/$PKGNAME to start it."
@@ -55,12 +56,12 @@ then
fi
COMMAND_ARGS=
if [ -z "$BASEDIR" ]
if [ -n "$BASEDIR" ]
then
COMMAND_ARGS="--basedir $BASEDIR $COMMAND_ARGS"
fi
if [ -z "$CONFIGFILE" ]
if [ -n "$CONFIGFILE" ]
then
COMMAND_ARGS="--config $CONFIGFILE $COMMAND_ARGS"
fi
@@ -91,7 +92,7 @@ do_start()
if [ $RETVAL != 0 ]; then
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile \
--exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK --nicelevel=$NICELEVEL \
-- $COMMAND_ARGS serve $DAEMON_ARGS
-- serve $COMMAND_ARGS $DAEMON_ARGS
RETVAL="$?"
fi
}
+12 -2
View File
@@ -15,8 +15,14 @@ import octoprint_setuptools
# Requirements for our application
INSTALL_REQUIRES = [
"flask>=0.9,<0.11",
"Jinja2>=2.8,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
# guarantee backwards compatibility for plugins and such with that
# version, hence we need to pin to a lower version for now. See #1697
"werkzeug>=0.8.3,<0.9",
"tornado>=4.0.2,<4.1",
"tornado==4.0.2", # pinned for now, we need to migrate to a newer tornado, but due
# to some voodoo needed to get large streamed uploads and downloads
# to work that is probably not completely straightforward and therefore
# something for post-1.3.0-stable release
"sockjs-tornado>=1.0.2,<1.1",
"PyYAML>=3.10,<3.11",
"Flask-Login>=0.2.2,<0.3",
@@ -40,9 +46,13 @@ INSTALL_REQUIRES = [
"feedparser>=5.2.1,<5.3",
"chainmap>=1.0.2,<1.1",
"future>=0.15,<0.16",
"scandir>=1.3,<1.4"
"scandir>=1.3,<1.4",
"websocket-client>=0.40,<0.41"
]
if sys.platform == "darwin":
INSTALL_REQUIRES.append("appdirs>=1.4.0")
# Additional requirements for optional install options
EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
+99 -13
View File
@@ -18,10 +18,6 @@ __revision__ = versions.get('full-revisionid', versions.get('full', None))
del versions
del get_versions
#~~ sane logging defaults
log.basicConfig()
#~~ try to ensure a sound SSL environment
urllib3_ssl = True
@@ -61,10 +57,21 @@ class FatalStartupError(BaseException):
def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
logging_config=None, debug=False, verbosity=0, uncaught_logger=None,
uncaught_handler=None, after_settings=None, after_logging=None):
uncaught_handler=None, safe_mode=False, after_preinit_logging=None,
after_settings=None, after_logging=None, after_safe_mode=None):
kwargs = dict()
logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler)
kwargs["logger"] = logger
kwargs["recorder"] = recorder
if callable(after_preinit_logging):
after_preinit_logging(**kwargs)
settings = init_settings(basedir, configfile)
kwargs["settings"] = settings
if callable(after_settings):
after_settings(settings)
after_settings(**kwargs)
logger = init_logging(settings,
use_logging_file=use_logging_file,
@@ -74,11 +81,20 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
verbosity=verbosity,
uncaught_logger=uncaught_logger,
uncaught_handler=uncaught_handler)
if callable(after_logging):
after_logging(logger)
kwargs["logger"] = logger
plugin_manager = init_pluginsystem(settings)
return settings, logger, plugin_manager
if callable(after_logging):
after_logging(**kwargs)
settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"])
safe_mode = safe_mode or settings_safe_mode
kwargs["safe_mode"] = safe_mode
if callable(after_safe_mode):
after_safe_mode(**kwargs)
plugin_manager = init_pluginsystem(settings, safe_mode=safe_mode)
return settings, logger, safe_mode, plugin_manager
def init_settings(basedir, configfile):
@@ -94,6 +110,45 @@ def init_settings(basedir, configfile):
raise FatalStartupError(message)
def preinit_logging(debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None):
config = {
"version": 1,
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "simple",
"stream": "ext://sys.stdout"
}
},
"loggers": {
"octoprint": {
"level": "DEBUG" if debug else "INFO"
},
"octoprint.util": {
"level": "INFO"
}
},
"root": {
"level": "WARN",
"handlers": ["console"]
}
}
logger = set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler)
from octoprint.logging.handlers import RecordingLogHandler
recorder = RecordingLogHandler(level=log.DEBUG)
log.getLogger().addHandler(recorder)
return logger, recorder
def init_logging(settings, use_logging_file=True, logging_file=None, default_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None):
"""Sets up logging."""
@@ -182,6 +237,11 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
else:
config = default_config
# configure logging globally
return set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler)
def set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handler):
# configure logging globally
import logging.config as logconfig
logconfig.dictConfig(config)
@@ -207,19 +267,45 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
if uncaught_handler is None:
def exception_logger(exc_type, exc_value, exc_tb):
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
uncaught_handler = exception_logger
sys.excepthook = uncaught_handler
return logger
def init_pluginsystem(settings):
def init_pluginsystem(settings, safe_mode=False):
"""Initializes the plugin manager based on the settings."""
from octoprint.plugin import plugin_manager
pm = plugin_manager(init=True, settings=settings)
import os
logger = log.getLogger(__name__)
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True),
settings.getBaseFolder("plugins")]
plugin_entry_points = ["octoprint.plugin"]
plugin_disabled_list = settings.get(["plugins", "_disabled"])
plugin_validators = []
if safe_mode:
def validator(phase, plugin_info):
if phase == "after_load":
setattr(plugin_info, "safe_mode_victim", not plugin_info.bundled)
setattr(plugin_info, "safe_mode_enabled", False)
elif phase == "before_enable":
if not plugin_info.bundled:
setattr(plugin_info, "safe_mode_enabled", True)
return False
return True
plugin_validators.append(validator)
from octoprint.plugin import plugin_manager
pm = plugin_manager(init=True,
plugin_folders=plugin_folders,
plugin_entry_points=plugin_entry_points,
plugin_disabled_list=plugin_disabled_list,
plugin_validators=plugin_validators)
settings_overlays = dict()
disabled_from_overlays = dict()
+34 -16
View File
@@ -13,10 +13,11 @@ import octoprint
class OctoPrintContext(object):
"""Custom context wrapping the standard options."""
def __init__(self, configfile=None, basedir=None, verbosity=0):
def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False):
self.configfile = configfile
self.basedir = basedir
self.verbosity = verbosity
self.safe_mode = safe_mode
pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True)
"""Decorator to pass in the :class:`OctoPrintContext` instance."""
@@ -46,15 +47,25 @@ def hidden_option(*param_decls, **attrs):
return f
return decorator
#~~ helper for settings context options
#~~ helper for setting context options
def set_ctx_obj_option(ctx, param, value):
"""Helper for setting eager options on the context."""
if ctx.obj is None:
ctx.obj = OctoPrintContext()
if hasattr(ctx.obj, param.name):
if value != param.default:
setattr(ctx.obj, param.name, value)
elif param.default is not None:
setattr(ctx.obj, param.name, param.default)
#~~ helper for retrieving context options
def get_ctx_obj_option(ctx, key, default, include_parents=True):
if include_parents and hasattr(ctx, "parent") and ctx.parent:
fallback = get_ctx_obj_option(ctx.parent, key, default)
else:
fallback = default
return getattr(ctx.obj, key, fallback)
#~~ helper for setting a lot of bulk options
@@ -95,6 +106,8 @@ def standard_options(hidden=False):
help="Specify the config file to use."),
factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Increase logging verbosity"),
factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Enable safe mode; disables all third party plugins")
]
return bulk_options(options)
@@ -102,13 +115,13 @@ def standard_options(hidden=False):
#~~ helper for settings legacy options we still have to support on "octoprint"
legacy_options = bulk_options([
hidden_option("--host", type=click.STRING),
hidden_option("--port", type=click.INT),
hidden_option("--logging", type=click.Path()),
hidden_option("--debug", "-d", is_flag=True),
hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"])),
hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid"),
hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True),
hidden_option("--host", type=click.STRING, callback=set_ctx_obj_option),
hidden_option("--port", type=click.INT, callback=set_ctx_obj_option),
hidden_option("--logging", type=click.Path(), callback=set_ctx_obj_option),
hidden_option("--debug", "-d", is_flag=True, callback=set_ctx_obj_option),
hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"]), callback=set_ctx_obj_option),
hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option),
hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option),
])
"""Legacy options available directly on the "octoprint" command in earlier versions.
Kept available for reasons of backwards compatibility, but hidden from the
@@ -120,14 +133,15 @@ from .server import server_commands
from .plugins import plugin_commands
from .dev import dev_commands
from .client import client_commands
from .config import config_commands
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
sources=[server_commands, plugin_commands, dev_commands, client_commands])
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands])
@standard_options()
@legacy_options
@click.version_option(version=octoprint.__version__)
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
@click.pass_context
def octo(ctx, debug, host, port, logging, daemon, pid, allow_root):
def octo(ctx, **kwargs):
if ctx.invoked_subcommand is None:
# We have to support calling the octoprint command without any
@@ -136,16 +150,20 @@ def octo(ctx, debug, host, port, logging, daemon, pid, allow_root):
# But better print a message to inform people that they should
# use the sub commands instead.
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
daemon = get_value("daemon")
if daemon:
click.echo("Daemon operation via \"octoprint --daemon "
"start|stop|restart\" is deprecated, please use "
"\"octoprint daemon start|stop|restart\" from now on")
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, debug=debug, pid=pid, daemon=daemon, allow_root=allow_root)
ctx.invoke(daemon_command, command=daemon, **kwargs)
else:
click.echo("Starting the server via \"octoprint\" is deprecated, "
"please use \"octoprint serve\" from now on.")
from octoprint.cli.server import serve_command
ctx.invoke(serve_command, debug=debug, host=host, port=port, logging=logging, allow_root=allow_root)
ctx.invoke(serve_command, **kwargs)
+4 -5
View File
@@ -9,7 +9,7 @@ import json
import octoprint_client
from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options
from octoprint.cli import get_ctx_obj_option
from octoprint import init_settings, FatalStartupError
@@ -35,13 +35,12 @@ def client_commands():
@click.option("--httppass", type=click.STRING)
@click.option("--https", is_flag=True)
@click.option("--prefix", type=click.STRING)
@pass_octoprint_ctx
@click.pass_context
def client(ctx, obj, host, port, httpuser, httppass, https, prefix):
def client(ctx, host, port, httpuser, httppass, https, prefix):
"""Basic API client."""
try:
obj.settings = init_settings(obj.basedir, obj.configfile)
octoprint_client.init_client(obj.settings, https=https, httpuser=httpuser, httppass=httppass, host=host, port=port, prefix=prefix)
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
octoprint_client.init_client(ctx.obj.settings, https=https, httpuser=httpuser, httppass=httppass, host=host, port=port, prefix=prefix)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True)
+218
View File
@@ -0,0 +1,218 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
import logging
from octoprint import init_settings, FatalStartupError
from octoprint.cli import pass_octoprint_ctx, standard_options, bulk_options, get_ctx_obj_option
import yaml
import json
import pprint
def _to_settings_path(path):
if not isinstance(path, (list, tuple)):
path = filter(lambda x: x, map(lambda x: x.strip(), path.split(".")))
return path
def _set_helper(settings, path, value, data_type=None):
path = _to_settings_path(path)
method = settings.set
if data_type is not None:
name = None
if data_type == bool:
name = "setBoolean"
elif data_type == float:
name = "setFloat"
elif data_type == int:
name = "setInt"
if name is not None:
method = getattr(settings, name)
method(path, value)
settings.save()
#~~ "octoprint config" commands
@click.group()
def config_commands():
pass
@config_commands.group(name="config")
@click.pass_context
def config(ctx):
"""Basic config manipulation."""
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
try:
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True)
ctx.exit(-1)
@config.command(name="set")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.argument("value", type=click.STRING)
@click.option("--bool", "as_bool", is_flag=True,
help="Interpret value as bool")
@click.option("--float", "as_float", is_flag=True,
help="Interpret value as float")
@click.option("--int", "as_int", is_flag=True,
help="Interpret value as int")
@click.option("--json", "as_json", is_flag=True,
help="Parse value from json")
@pass_octoprint_ctx
@click.pass_context
def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
"""Sets a config path to the provided value."""
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
data_type = None
if as_bool:
data_type = bool
elif as_float:
data_type = float
elif as_int:
data_type = int
_set_helper(ctx.obj.settings, path, value, data_type=data_type)
@config.command(name="remove")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.pass_context
def remove_command(ctx, path):
"""Removes a config path."""
_set_helper(ctx.obj.settings, path, None)
@config.command(name="append_value")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.argument("value", type=click.STRING)
@click.option("--json", "as_json", is_flag=True)
@click.pass_context
def append_value_command(ctx, path, value, as_json=False):
"""Appends value to list behind config path."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot append to non-list value at given path", err=True)
ctx.exit(-1)
current.append(value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="insert_value")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.argument("index", type=click.INT)
@click.argument("value", type=click.STRING)
@click.option("--json", "as_json", is_flag=True)
@click.pass_context
def insert_value_command(ctx, path, index, value, as_json=False):
"""Inserts value at index of list behind config key."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot insert into non-list value at given path", err=True)
ctx.exit(-1)
current.insert(index, value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="remove_value")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.argument("value", type=click.STRING)
@click.option("--json", "as_json", is_flag=True)
@pass_octoprint_ctx
@click.pass_context
def remove_value_command(ctx, path, value, as_json=False):
"""Removes value from list at config path."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot remove value from non-list value at given path", err=True)
ctx.exit(-1)
if not value in current:
click.echo("Value is not contained in list at given path")
ctx.exit()
current.remove(value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="get")
@click.argument("path", type=click.STRING)
@click.option("--json", "as_json", is_flag=True,
help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True,
help="Output value formatted as YAML")
@click.option("--raw", "as_raw", is_flag=True,
help="Output value as raw string representation")
@standard_options(hidden=True)
@click.pass_context
def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
"""Retrieves value from config path."""
path = _to_settings_path(path)
value = ctx.obj.settings.get(path, merged=True)
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
click.echo(output)
+3 -3
View File
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import click
import logging
from octoprint.cli import pass_octoprint_ctx, OctoPrintContext
from octoprint.cli import pass_octoprint_ctx, OctoPrintContext, get_ctx_obj_option
#~~ "octoprint plugin:command" commands
@@ -50,8 +50,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
# context (basedir and configfile)
from octoprint import init_settings, init_pluginsystem, FatalStartupError
try:
self.settings = init_settings(ctx.obj.basedir, ctx.obj.configfile)
self.plugin_manager = init_pluginsystem(self.settings)
self.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
self.plugin_manager = init_pluginsystem(self.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings or the plugin system.", err=True)
+84 -30
View File
@@ -9,15 +9,28 @@ import click
import logging
import sys
from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options
from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, octoprint_daemon = None):
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode, octoprint_daemon=None):
"""Initializes the environment and starts up the server."""
from octoprint import init_platform, __display_version__, FatalStartupError
def log_startup(_):
logging.getLogger("octoprint.server").info("Starting OctoPrint {}".format(__display_version__))
def log_startup(recorder=None, safe_mode=None, **kwargs):
logger = logging.getLogger("octoprint.server")
logger.info("Starting OctoPrint {}".format(__display_version__))
if safe_mode:
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
if recorder and len(recorder):
logger.info("--- Logged during platform initialization: ---")
from octoprint.logging.handlers import CombinedLogHandler
handler = CombinedLogHandler(*logging.getLogger().handlers)
recorder.setTarget(handler)
recorder.flush()
logger.info("----------------------------------------------")
from octoprint import urllib3_ssl
if not urllib3_ssl:
@@ -30,13 +43,14 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl")
try:
settings, _, plugin_manager = init_platform(basedir,
configfile,
logging_file=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=__name__,
after_logging=log_startup)
settings, _, safe_mode, plugin_manager = init_platform(basedir,
configfile,
logging_file=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=__name__,
safe_mode=safe_mode,
after_safe_mode=log_startup)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error starting up OctoPrint.", err=True)
@@ -47,6 +61,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
host=host,
port=port,
debug=debug,
safe_mode=safe_mode,
allow_root=allow_root,
octoprint_daemon=octoprint_daemon)
octoprint_server.run()
@@ -54,51 +69,87 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
#~~ server options
server_options = bulk_options([
click.option("--host", type=click.STRING,
click.option("--host", type=click.STRING, callback=set_ctx_obj_option,
help="Specify the host on which to bind the server."),
click.option("--port", type=click.INT,
click.option("--port", type=click.INT, callback=set_ctx_obj_option,
help="Specify the port on which to bind the server."),
click.option("--logging", type=click.Path(),
click.option("--logging", type=click.Path(), callback=set_ctx_obj_option,
help="Specify the config file to use for configuring logging."),
click.option("--iknowwhatimdoing", "allow_root", is_flag=True,
click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option,
help="Allow OctoPrint to run as user root."),
click.option("--debug", is_flag=True, help="Enable debug mode"),
click.option("--debug", is_flag=True, callback=set_ctx_obj_option,
help="Enable debug mode.")
])
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
daemon_options = bulk_options([
click.option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option,
help="Pidfile to use for daemonizing.")
])
"""Decorator to add the options for the daemon subcommand: ``--pid``."""
#~~ "octoprint serve" and "octoprint daemon" commands
@click.group()
@pass_octoprint_ctx
def server_commands(obj):
def server_commands():
pass
@server_commands.command(name="serve")
@server_options
@standard_options(hidden=True)
@pass_octoprint_ctx
def serve_command(obj, host, port, logging, allow_root, debug):
@click.pass_context
def serve_command(ctx, **kwargs):
"""Starts the OctoPrint server."""
run_server(obj.basedir, obj.configfile, host, port, debug,
allow_root, logging, obj.verbosity)
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
host = get_value("host")
port = get_value("port")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
run_server(basedir, configfile, host, port, debug,
allow_root, logging, verbosity, safe_mode)
@server_commands.command(name="daemon")
@click.option("--pid", type=click.Path(), default="/tmp/octoprint.pid",
help="Pidfile to use for daemonizing.")
@server_options
@daemon_options
@standard_options(hidden=True)
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
metavar="start|stop|restart|status")
@pass_octoprint_ctx
def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, command):
@click.pass_context
def daemon_command(ctx, command, **kwargs):
"""
Starts, stops or restarts in daemon mode.
Please note that daemon mode is only supported under Linux right now.
"""
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
host = get_value("host")
port = get_value("port")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
pid = get_value("pid")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
if sys.platform == "darwin" or sys.platform == "win32":
click.echo("Sorry, daemon mode is only supported under Linux right now",
file=sys.stderr)
@@ -111,7 +162,7 @@ def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, c
from octoprint.daemon import Daemon
class OctoPrintDaemon(Daemon):
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity):
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode):
Daemon.__init__(self, pidfile)
self._basedir = basedir
@@ -122,12 +173,15 @@ def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, c
self._allow_root = allow_root
self._logging_config = logging_config
self._verbosity = verbosity
self._safe_mode = safe_mode
def run(self):
run_server(self._basedir, self._configfile, self._host, self._port, self._debug, self._allow_root, self._logging_config, self._verbosity, self)
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
octoprint_daemon=self)
octoprint_daemon = OctoPrintDaemon(pid, octoprint_ctx.basedir, octoprint_ctx.configfile,
host, port, debug, allow_root, logging, octoprint_ctx.verbosity)
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
safe_mode)
if command == "start":
octoprint_daemon.start()
+1
View File
@@ -78,6 +78,7 @@ class Events(object):
CONVEYOR = "Conveyor"
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
# Timelapse
+24 -5
View File
@@ -397,13 +397,10 @@ class FileManager(object):
if hook_file_object is not None:
file_object = hook_file_object
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
absolute_path = self._storage(destination).path_on_disk(file_path)
_, file_name = self._storage(destination).split_path(file_path)
if analysis is None:
file_type = get_file_type(absolute_path)
if file_type:
queue_entry = QueueEntry(file_name, file_path, file_type[-1], destination, absolute_path, printer_profile)
queue_entry = self._analysis_queue_entry(destination, file_path, printer_profile=printer_profile)
if queue_entry:
self._analysis_queue.enqueue(queue_entry, high_priority=True)
else:
self._add_analysis_result(destination, path, analysis)
@@ -412,6 +409,8 @@ class FileManager(object):
return file_path
def remove_file(self, destination, path):
queue_entry = self._analysis_queue_entry(destination, path)
self._analysis_queue.dequeue(queue_entry)
self._storage(destination).remove_file(path)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
@@ -420,6 +419,8 @@ class FileManager(object):
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def move_file(self, destination, source, dst):
queue_entry = self._analysis_queue_entry(destination, source)
self._analysis_queue.dequeue(queue_entry)
self._storage(destination).move_file(source, dst)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
@@ -429,7 +430,10 @@ class FileManager(object):
return folder_path
def remove_folder(self, destination, path, recursive=True):
self._analysis_queue.dequeue_folder(destination, path)
self._analysis_queue.pause()
self._storage(destination).remove_folder(path, recursive=recursive)
self._analysis_queue.resume()
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def copy_folder(self, destination, source, dst):
@@ -437,7 +441,10 @@ class FileManager(object):
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def move_folder(self, destination, source, dst):
self._analysis_queue.dequeue_folder(destination, source)
self._analysis_queue.pause()
self._storage(destination).move_folder(source, dst)
self._analysis_queue.resume()
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def get_metadata(self, destination, path):
@@ -542,3 +549,15 @@ class FileManager(object):
def _on_analysis_finished(self, entry, result):
self._add_analysis_result(entry.location, entry.path, result)
def _analysis_queue_entry(self, destination, path, printer_profile=None):
if printer_profile is None:
printer_profile = self._printer_profile_manager.get_current_or_default()
absolute_path = self._storage(destination).path_on_disk(path)
_, file_name = self._storage(destination).split_path(path)
file_type = get_file_type(absolute_path)
if file_type:
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile)
else:
return None
+69 -26
View File
@@ -17,6 +17,7 @@ import collections
import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
import octoprint.util.gcodeInterpreter as gcodeInterpreter
@@ -40,6 +41,12 @@ class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, locatio
return "{location}:{path}".format(location=self.location, path=self.path)
class AnalysisAborted(Exception):
def __init__(self, reenqueue=True, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.reenqueue = reenqueue
class AnalysisQueue(object):
"""
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
@@ -77,6 +84,16 @@ class AnalysisQueue(object):
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
return True
def dequeue(self, entry):
if not entry.type in self._queues:
return False
self._queues[entry.type].dequeue(entry.location, entry.path)
def dequeue_folder(self, destination, path):
for queue in self._queues.values():
queue.dequeue_folder(destination, path)
def pause(self):
for queue in self._queues.values():
queue.pause()
@@ -112,8 +129,10 @@ class AbstractAnalysisQueue(object):
.. automethod:: _do_abort
"""
LOW_PRIO = 0
HIGH_PRIO = 100
LOW_PRIO = 100
LOW_PRIO_ABORTED = 75
HIGH_PRIO = 50
HIGH_PRIO_ABORTED = 0
def __init__(self, finished_callback):
self._logger = logging.getLogger(__name__)
@@ -123,11 +142,15 @@ class AbstractAnalysisQueue(object):
self._active = threading.Event()
self._active.set()
self._done = threading.Event()
self._done.clear()
self._currentFile = None
self._currentProgress = None
self._queue = queue.PriorityQueue()
self._current = None
self._current_highprio = False
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
@@ -153,7 +176,24 @@ class AbstractAnalysisQueue(object):
self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry))
prio = self.__class__.LOW_PRIO
self._queue.put((prio, entry))
self._queue.put((prio, entry, high_priority))
if high_priority and self._current is not None and not self._current_highprio:
self._logger.debug("Aborting current analysis in favor of high priority one")
self._do_abort()
def dequeue(self, location, path):
if self._current is not None and self._current.location == location \
and self._current.path == path:
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def dequeue_folder(self, location, path):
if self._current is not None and self._current.location == location \
and self._current.path.startswith(path + "/"):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def pause(self):
"""
@@ -175,24 +215,23 @@ class AbstractAnalysisQueue(object):
self._active.set()
def _work(self):
aborted = None
while True:
if aborted is not None:
entry = aborted
aborted = None
self._logger.debug("Got an aborted analysis job for entry {entry}, processing this instead of first item in queue".format(**locals()))
else:
(priority, entry) = self._queue.get()
self._logger.debug("Processing entry {entry} from queue (priority {priority})".format(**locals()))
(priority, entry, high_priority) = self._queue.get()
self._logger.debug("Processing entry {} from queue (priority {})".format(entry, priority))
self._active.wait()
try:
self._analyze(entry, high_priority=(priority == self.__class__.HIGH_PRIO))
self._analyze(entry, high_priority=high_priority)
self._queue.task_done()
except gcodeInterpreter.AnalysisAborted:
aborted = entry
self._logger.debug("Running analysis of entry {entry} aborted".format(**locals()))
self._done.set()
except AnalysisAborted as ex:
if ex.reenqueue:
self._queue.put((self.__class__.HIGH_PRIO_ABORTED if high_priority else self.__class__.LOW_PRIO_ABORTED,
entry,
high_priority))
self._logger.debug("Running analysis of entry {} aborted".format(entry))
self._queue.task_done()
self._done.set()
else:
time.sleep(1.0)
@@ -202,10 +241,12 @@ class AbstractAnalysisQueue(object):
return
self._current = entry
self._current_highprio = high_priority
self._current_progress = 0
try:
self._logger.info("Starting analysis of {entry}".format(**locals()))
start_time = time.time()
self._logger.info("Starting analysis of {}".format(entry))
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
"path": entry.path,
"origin": entry.location,
@@ -217,7 +258,7 @@ class AbstractAnalysisQueue(object):
result = self._do_analysis(high_priority=high_priority)
except TypeError:
result = self._do_analysis()
self._logger.debug("Analysis of entry {entry} finished, notifying callback".format(**locals()))
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, time.time() - start_time))
self._finished_callback(self._current, result)
finally:
self._current = None
@@ -237,7 +278,7 @@ class AbstractAnalysisQueue(object):
"""
return None
def _do_abort(self):
def _do_abort(self, reenqueue=True):
"""
Aborts analysis of the current entry. Needs to be overridden by sub classes.
"""
@@ -266,11 +307,11 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
def _do_analysis(self, high_priority=False):
try:
def throttle():
time.sleep(0.01)
throttle_callback = throttle
if high_priority:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
if throttle > 0:
def throttle_callback():
time.sleep(throttle)
else:
throttle_callback = None
self._gcode = gcodeInterpreter.gcode()
@@ -289,9 +330,11 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
"volume": self._gcode.extrusionVolume[i]
}
return result
except gcodeInterpreter.AnalysisAborted as ex:
raise AnalysisAborted(reenqueue=ex.reenqueue)
finally:
self._gcode = None
def _do_abort(self):
def _do_abort(self, reenqueue=True):
if self._gcode:
self._gcode.abort()
self._gcode.abort(reenqueue=reenqueue)
+13 -8
View File
@@ -473,10 +473,10 @@ class LocalFileStorage(StorageInterface):
if not metadata:
metadata = dict()
for entry in scandir(path):
if is_hidden_path(entry.name) or not octoprint.filemanager.valid_file_type(entry.name):
if is_hidden_path(entry.name):
continue
if entry.is_file():
if entry.is_file() and octoprint.filemanager.valid_file_type(entry.name):
if not entry.name in metadata or not isinstance(metadata[entry.name], dict) or not "analysis" in metadata[entry.name]:
printer_profile_rels = self.get_link(entry.path, "printerprofile")
if printer_profile_rels:
@@ -511,7 +511,7 @@ class LocalFileStorage(StorageInterface):
filepath = self.sanitize_path(filepath)
path = self.sanitize_path(path)
return filepath.startswith(path)
return filepath == path or filepath.startswith(path + os.sep)
def file_exists(self, path):
path, name = self.sanitize(path)
@@ -1123,11 +1123,16 @@ class LocalFileStorage(StorageInterface):
# no hidden files and folders
continue
entry_name = entry.name
entry_path = entry.path
entry_is_file = entry.is_file()
entry_is_dir = entry.is_dir()
entry_stat = entry.stat()
try:
entry_name = entry.name
entry_path = entry.path
entry_is_file = entry.is_file()
entry_is_dir = entry.is_dir()
entry_stat = entry.stat()
except:
# error while trying to fetch file metadata, that might be thanks to file already having
# been moved or deleted - ignore it and continue
continue
try:
new_entry_name, new_entry_path = self._sanitize_entry(entry_name, path, entry_path)
+53
View File
@@ -81,3 +81,56 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
self.cleanupFiles()
if not self.delay:
self.stream = self._open()
class RecordingLogHandler(logging.Handler):
def __init__(self, target=None, level=logging.NOTSET):
logging.Handler.__init__(self, level=level)
self._buffer = []
self._target = target
def emit(self, record):
self._buffer.append(record)
def setTarget(self, target):
self._target = target
def flush(self):
if not self._target:
return
self.acquire()
try:
for record in self._buffer:
self._target.handle(record)
self._buffer = []
finally:
self.release()
def close(self):
self.flush()
self.acquire()
try:
self._buffer = []
finally:
self.release()
def __len__(self):
return len(self._buffer)
class CombinedLogHandler(logging.Handler):
def __init__(self, *handlers):
logging.Handler.__init__(self)
self._handlers = handlers
def setHandlers(self, *handlers):
self._handlers = handlers
def handle(self, record):
self.acquire()
try:
if self._handlers:
for handler in self._handlers:
handler.handle(record)
finally:
self.release()
+21 -33
View File
@@ -42,9 +42,10 @@ def _validate_plugin(phase, plugin_info):
if not "octoprint.accesscontrol.appkey" in hooks:
hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
return True
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None, settings=None):
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
"""
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
singleton.
@@ -87,14 +88,6 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
else:
if init:
if settings is None:
settings = s()
if plugin_folders is None:
plugin_folders = (
settings.getBaseFolder("plugins"),
(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")), True)
)
if plugin_types is None:
plugin_types = [StartupPlugin,
ShutdownPlugin,
@@ -109,22 +102,17 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
ProgressPlugin,
WizardPlugin,
UiPlugin]
if plugin_entry_points is None:
plugin_entry_points = "octoprint.plugin"
if plugin_disabled_list is None:
plugin_disabled_list = settings.get(["plugins", "_disabled"])
if plugin_restart_needing_hooks is None:
plugin_restart_needing_hooks = [
"octoprint.server.http"
]
plugin_restart_needing_hooks = ["octoprint.server.http"]
if plugin_obsolete_hooks is None:
plugin_obsolete_hooks = [
"octoprint.comm.protocol.gcode"
]
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
if plugin_validators is None:
plugin_validators = [
_validate_plugin
]
plugin_validators = [_validate_plugin]
else:
plugin_validators.append(_validate_plugin)
_instance = PluginManager(plugin_folders,
plugin_types,
@@ -145,7 +133,7 @@ def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_prepr
Arguments:
plugin_key (string): The plugin identifier for which to create the settings instance.
defaults (dict): The default settings for the plugin.
defaults (dict): The default settings for the plugin, if different from get_settings_defaults.
get_preprocessors (dict): The getter preprocessors for the plugin.
set_preprocessors (dict): The setter preprocessors for the plugin.
settings (octoprint.settings.Settings): The settings instance to use.
@@ -180,13 +168,12 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
return None
try:
defaults = instance.get_settings_defaults()
get_preprocessors, set_preprocessors = instance.get_settings_preprocessors()
except:
logging.getLogger(__name__).exception("Error while retrieving defaults or preprocessors for plugin {}".format(plugin_key))
logging.getLogger(__name__).exception("Error while retrieving preprocessors for plugin {}".format(plugin_key))
return None
return plugin_settings(plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None):
@@ -315,11 +302,12 @@ class PluginSettings(object):
self.settings = settings
self.plugin_key = plugin_key
if defaults is None:
defaults = dict()
self.defaults = dict(plugins=dict())
self.defaults["plugins"][plugin_key] = defaults
self.defaults["plugins"][plugin_key]["_config_version"] = None
if defaults is not None:
self.defaults = dict(plugins=dict())
self.defaults["plugins"][plugin_key] = defaults
self.defaults["plugins"][plugin_key]["_config_version"] = None
else:
self.defaults = None
if get_preprocessors is None:
get_preprocessors = dict()
@@ -345,14 +333,14 @@ class PluginSettings(object):
return result
def add_getter_kwargs(kwargs):
if not "defaults" in kwargs:
if not "defaults" in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.get_preprocessors)
return kwargs
def add_setter_kwargs(kwargs):
if not "defaults" in kwargs:
if not "defaults" in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.set_preprocessors)
+17 -2
View File
@@ -149,6 +149,8 @@ class PluginInfo(object):
self._license = license
def validate(self, phase, additional_validators=None):
result = True
if phase == "before_load":
# if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__
if hasattr(self.instance, self.__class__.attr_init):
@@ -183,7 +185,9 @@ class PluginInfo(object):
if additional_validators is not None:
for validator in additional_validators:
validator(phase, self)
result = result and validator(phase, self)
return result
def __str__(self):
if self.version:
@@ -448,6 +452,12 @@ class PluginManager(object):
if logging_prefix is None:
logging_prefix = ""
if plugin_folders is None:
plugin_folders = []
if plugin_types is None:
plugin_types = []
if plugin_entry_points is None:
plugin_entry_points = []
if plugin_disabled_list is None:
plugin_disabled_list = []
@@ -740,7 +750,9 @@ class PluginManager(object):
plugin = self.plugins[name]
try:
plugin.validate("before_load", additional_validators=self.plugin_validators)
if not plugin.validate("before_load", additional_validators=self.plugin_validators):
return
plugin.load()
plugin.validate("after_load", additional_validators=self.plugin_validators)
self.on_plugin_loaded(name, plugin)
@@ -802,6 +814,9 @@ class PluginManager(object):
raise PluginCantEnable(name, "Dependency on obsolete hooks detected, full functionality cannot be guaranteed")
try:
if not plugin.validate("before_enable", additional_validators=self.plugin_validators):
return False
plugin.enable()
self._activate_plugin(name, plugin)
except PluginLifecycleException as e:
+23 -3
View File
@@ -1368,14 +1368,17 @@ class SettingsPlugin(OctoPrintPlugin):
to retrieve the data in the correct format.
The default implementation will also replace any paths that have been restricted by your plugin through
:func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with ``None`` values where necessary.
:func:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths` with either the provided
default value (if one was provided), an empty dictionary (as fallback for restricted dictionaries), an
empty list (as fallback for restricted lists) or ``None`` values where necessary.
Make sure to do your own restriction if you decide to fully overload this method.
:return: the current settings of the plugin, as a dictionary
"""
from flask.ext.login import current_user
import copy
data = self._settings.get_all_data()
data = copy.deepcopy(self._settings.get_all_data(merged=True))
if self.config_version_key in data:
del data[self.config_version_key]
@@ -1397,8 +1400,25 @@ class SettingsPlugin(OctoPrintPlugin):
node = node[entry]
key = path[-1]
default_value_available = False
default_value = None
if isinstance(key, (list, tuple)):
# key, default_value tuple
key, default_value = key
default_value_available = True
if key in node:
node[key] = None
if default_value_available:
if callable(default_value):
default_value = default_value()
node[key] = default_value
else:
if isinstance(node[key], dict):
node[key] = dict()
elif isinstance(node[key], (list, tuple)):
node[key] = []
else:
node[key] = None
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous(),
admin=lambda: current_user is not None and not current_user.is_anonymous() and current_user.is_admin(),
@@ -71,7 +71,7 @@ $(function() {
});
};
self.onWizardTabChange = function(current, next) {
self.onBeforeWizardTabChange = function(next, current) {
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
return true;
}
@@ -13,19 +13,19 @@ to OctoPrint, you can also configure additional printer profiles under Settings
<div class="tab-content scrollable">
<!-- ko with: editor -->
<div id="wizard_plugin_corewizard_printerprofile_general" class="tab-pane active">
{% include '_snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
</div>
<div id="wizard_plugin_corewizard_printerprofile_buildvolume" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
</div>
<div id="wizard_plugin_corewizard_printerprofile_axes" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
</div>
<div id="wizard_plugin_corewizard_printerprofile_extruder" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
</div>
<!-- /ko -->
</div>
@@ -8,12 +8,12 @@
<h4>{{ _('OctoPrint related commands') }}</h4>
<form class="form-horizontal" data-bind="with: settingsViewModel">
{% include "_snippets/settings/server/serverCommandServerRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandServerRestart.jinja2" %}
</form>
<h4>{{ _('System related commands') }}</h4>
<form class="form-horizontal" data-bind="with: settingsViewModel">
{% include "_snippets/settings/server/serverCommandSystemRestart.jinja2" %}
{% include "_snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
</form>
@@ -26,8 +26,8 @@
</p>{% endtrans %}
<form class="form-horizontal" data-bind="with: settingsViewModel">
{% include "_snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "_snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
{% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
</form>
<h4>{{ _('Timelapse Recordings') }}</h4>
@@ -38,5 +38,5 @@
</p>{% endtrans %}
<form class="form-horizontal" data-bind="with: settingsViewModel">
{% include "_snippets/settings/webcam/ffmpegPath.jinja2" %}
{% include "snippets/settings/webcam/ffmpegPath.jinja2" %}
</form>
+29 -12
View File
@@ -246,11 +246,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
machinecode_path = path + ".gco"
if position and isinstance(position, dict) and "x" in position and "y" in position:
posX = position["x"]
posY = position["y"]
pos_x = position["x"]
pos_y = position["y"]
else:
posX = None
posY = None
pos_x = None
pos_y = None
if on_progress:
if not on_progress_args:
@@ -266,7 +266,24 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
working_dir = os.path.dirname(executable)
engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
slicing_profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y)
# NOTE: We can assume an extruder count of 1 here since the only way we currently
# support dual extrusion in this implementation is by using the second extruder for support (which
# the engine conversion will automatically detect and adapt accordingly).
#
# We currently do only support STL files as sliceables, which by default can only contain one mesh,
# so no risk of having to slice multi-objects at the moment, which would necessitate a full analysis
# of the objects to slice to determine amount of needed extruders to use here. If we ever decide to
# also support dual extrusion slicing (including composition from multiple STLs or support for OBJ or
# AMF files and the like), this code needs to be adapted!
#
# The extruder count is needed to decide which start/end gcode will be used from the Cura profile.
# Stock Cura implementation counts the number of objects in the scene for this (and also takes a look
# at the support usage, like the engine conversion here does). We only ever have one object.
engine_settings = self._convert_to_engine(profile_path, printer_profile,
pos_x=pos_x, pos_y=pos_y,
used_extruders=1)
# Start building the argument list for the CuraEngine command execution
args = [executable, '-v', '-p']
@@ -375,11 +392,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
if not tool_key in analysis["filament"]:
analysis["filament"][tool_key] = dict()
if profile.get_float("filament_diameter") != None:
if profile.get("gcode_flavor") == GcodeFlavors.ULTIGCODE or profile.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
analysis["filament"][tool_key] = _get_usage_from_volume(filament, profile.get_float("filament_diameter"))
if slicing_profile.get_float("filament_diameter") is not None:
if slicing_profile.get("gcode_flavor") == GcodeFlavors.ULTIGCODE or slicing_profile.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
analysis["filament"][tool_key] = _get_usage_from_volume(filament, slicing_profile.get_float("filament_diameter"))
else:
analysis["filament"][tool_key] = _get_usage_from_length(filament, profile.get_float("filament_diameter"))
analysis["filament"][tool_key] = _get_usage_from_length(filament, slicing_profile.get_float("filament_diameter"))
except:
pass
@@ -442,9 +459,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
with octoprint.util.atomic_write(path, "wb", max_permissions=0o666) as f:
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
return profile.convert_to_engine()
def _convert_to_engine(self, profile_path, printer_profile, pos_x=None, pos_y=None, used_extruders=1):
profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y)
return profile.convert_to_engine(used_extruders=used_extruders)
def _sanitize_name(name):
if name is None:
+44 -32
View File
@@ -63,12 +63,14 @@ defaults = dict(
solid_top=True,
solid_bottom=True,
fill_overlap=15,
perimeter_before_infill=False,
# speeds
print_speed=50.0,
travel_speed=150.0,
bottom_layer_speed=20.0,
infill_speed=0.0,
solidarea_speed=0.0,
outer_shell_speed=0.0,
inner_shell_speed=0.0,
@@ -117,8 +119,11 @@ defaults = dict(
raft_base_linewidth=1.0,
raft_interface_thickness=0.27,
raft_interface_linewidth=0.4,
raft_airgap_all=0.0,
raft_airgap=0.22,
raft_surface_layers=2,
raft_surface_thickness=0.27,
raft_surface_linewidth=0.4,
# repairing
fix_horrible_union_all_type_a=True,
@@ -597,8 +602,8 @@ class Profile(object):
diameters = self._get("filament_diameter")
if not match.group(1):
return diameters[0]
index = int(match.group(1))
if index >= len(diameters):
index = int(match.group(1)) - 1
if index >= len(diameters) or index < 0:
return 0.0
return diameters[index]
@@ -610,8 +615,8 @@ class Profile(object):
temperatures = self._get("print_temperature")
if not match.group(1):
return temperatures[0]
index = int(match.group(1))
if index >= len(temperatures):
index = int(match.group(1)) - 1
if index >= len(temperatures) or index < 0:
return 0.0
return temperatures[index]
@@ -669,9 +674,7 @@ class Profile(object):
return default
return int(value * 1000)
def get_gcode_template(self, key):
extruder_count = self.get_int("extruder_amount")
def get_gcode_template(self, key, extruder_count=1):
if key in self._profile:
gcode = self._profile[key]
else:
@@ -731,7 +734,7 @@ class Profile(object):
return pre + str(f)
def get_gcode(self, key):
def get_gcode(self, key, extruder_count=1):
prefix = ""
postfix = ""
@@ -741,11 +744,11 @@ class Profile(object):
return ""
if key == "start_gcode":
contents = self.get_gcode_template("start_gcode")
contents = self.get_gcode_template("start_gcode", extruder_count=extruder_count)
prefix += self.get_start_gcode_prefix(contents)
else:
contents = self.get_gcode_template(key)
contents = self.get_gcode_template(key, extruder_count=extruder_count)
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
@@ -754,9 +757,13 @@ class Profile(object):
prefix = ""
gcode_parameter_key = "S"
if self.get("gcode_flavor") == GcodeFlavors.MACH3:
gcode_parameter_key = "P"
e_steps = self.get_float("steps_per_e")
if e_steps > 0:
prefix += "M92 E{e_steps}\n" % (e_steps)
prefix += "M92 E{e_steps}\n".format(e_steps=e_steps)
temp = self.get_float("print_temperature")
bed_temp = 0
@@ -765,30 +772,30 @@ class Profile(object):
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
if include_bed_temp:
prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp)
prefix += "M140 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp)
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
if extruder_count > 0:
def temp_line(temp, extruder, template):
def temp_line(temp, extruder, param, template):
t = temp
if extruder > 0:
print_temp = self.get_float("print_temperature%d" % (extruder + 1))
if print_temp > 0:
t = print_temp
return template.format(extruder=extruder, temp=t)
return template.format(extruder=extruder, temp=t, param=param)
prefix_preheat = ""
prefix_waitheat = ""
for n in range(0, extruder_count):
if n > 0:
prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
prefix_preheat += temp_line(temp, n, gcode_parameter_key, "M104 T{extruder} {param}{temp}\n")
prefix_waitheat += temp_line(temp, n, gcode_parameter_key, "M109 T{extruder} {param}{temp}\n")
prefix += prefix_preheat + prefix_waitheat + "T0\n"
else:
prefix += "M109 S{temp}\n".format(temp=temp)
prefix += "M109 {param}{temp}\n".format(param=gcode_parameter_key, temp=temp)
if include_bed_temp:
prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp)
prefix += "M190 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp)
return prefix
@@ -822,7 +829,7 @@ class Profile(object):
if layer_height == 0.0:
return 1
import math
return int(math.ceil(solid_thickness / (layer_height - 0.0001)))
return int(math.ceil((solid_thickness - 0.0001) / layer_height))
def calculate_minimal_extruder_count(self):
extruder_count = self.get("extruder_amount")
@@ -835,7 +842,7 @@ class Profile(object):
return 1
def get_pos_x(self):
if self._posX:
if self._posX is not None:
try:
return int(float(self._posX))
except ValueError:
@@ -844,7 +851,7 @@ class Profile(object):
return int(self.get_float("machine_width") / 2.0 ) if not self.get_boolean("machine_center_is_zero") else 0.0
def get_pos_y(self):
if self._posY:
if self._posY is not None:
try:
return int(float(self._posY))
except ValueError:
@@ -852,13 +859,14 @@ class Profile(object):
return int(self.get_float("machine_depth") / 2.0) if not self.get_boolean("machine_center_is_zero") else 0.0
def convert_to_engine(self):
def convert_to_engine(self, used_extruders=1):
edge_width, line_count = self.calculate_edge_width_and_line_count()
solid_layer_count = self.calculate_solid_layer_count()
extruder_count = self.get_int("extruder_amount")
minimal_extruder_count = self.calculate_minimal_extruder_count()
actual_extruder_count = max(minimal_extruder_count, used_extruders)
settings = {
"layerThickness": self.get_microns("layer_height"),
@@ -871,12 +879,14 @@ class Profile(object):
"downSkinCount": solid_layer_count if self.get_boolean("solid_bottom") else 0,
"upSkinCount": solid_layer_count if self.get_boolean("solid_top") else 0,
"infillOverlap": self.get_int("fill_overlap"),
"perimeterBeforeInfill": 1 if self.get_boolean("perimeter_before_infill") else 0,
"initialSpeedupLayers": int(4),
"initialLayerSpeed": self.get_int("bottom_layer_speed"),
"printSpeed": self.get_int("print_speed"),
"infillSpeed": self.get_int("infill_speed") if self.get_int("infill_speed") > 0 else self.get_int("print_speed"),
"inset0Speed": self.get_int("outer_shell_speed") if self.get_int("outer_shell_speed") > 0 else self.get_int("print_speed"),
"insetXSpeed": self.get_int("inner_shell_speed") if self.get_int("inner_shell_speed") > 0 else self.get_int("print_speed"),
"skinSpeed": self.get_int("solidarea_speed") if self.get_int("solidarea_speed") > 0 > 0 else self.get_int("print_speed"),
"moveSpeed": self.get_int("travel_speed"),
"fanSpeedMin": self.get_int("fan_speed") if self.get_boolean("fan_enabled") else 0,
"fanSpeedMax": self.get_int("fan_speed_max") if self.get_boolean("fan_enabled") else 0,
@@ -892,22 +902,23 @@ class Profile(object):
"retractionAmountExtruderSwitch": self.get_microns("retraction_dual_amount"),
"retractionZHop": self.get_microns("retraction_hop"),
"minimalExtrusionBeforeRetraction": self.get_microns("retraction_minimal_extrusion"),
"enableCombing": 1 if self.get("retraction_combing") == RetractionCombingTypes.ALL else (2 if self.get("retraction_combing") == RetractionCombingTypes.NO_SKIN else 0),
"multiVolumeOverlap": self.get_microns("overlap_dual"),
"objectSink": max(0, self.get_microns("object_sink")),
"minimalLayerTime": self.get_int("cool_min_layer_time"),
"minimalFeedrate": self.get_int("cool_min_feedrate"),
"coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0,
"enableCombing": 1 if self.get("retraction_combing") == RetractionCombingTypes.ALL else (2 if self.get("retraction_combing") == RetractionCombingTypes.NO_SKIN else 0),
# model positioning
"posx": self.get_pos_x() * 1000, # in microns
"posy": self.get_pos_y() * 1000, # in microns
# gcodes
"startCode": self.get_gcode("start_gcode"),
"endCode": self.get_gcode("end_gcode"),
"preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode"),
"postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode"),
"startCode": self.get_gcode("start_gcode", extruder_count=actual_extruder_count),
"endCode": self.get_gcode("end_gcode", extruder_count=actual_extruder_count),
"preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode", extruder_count=actual_extruder_count),
"postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode", extruder_count=actual_extruder_count),
# fixing
"fixHorrible": 0,
@@ -952,12 +963,13 @@ class Profile(object):
settings["raftInterfaceThickness"] = self.get_microns("raft_interface_thickness")
settings["raftInterfaceLinewidth"] = self.get_microns("raft_interface_linewidth")
settings["raftInterfaceLineSpacing"] = self.get_microns("raft_interface_linewidth") * 2
settings["raftAirGapLayer0"] = self.get_microns("raft_airgap")
settings["raftAirGapLayer0"] = self.get_microns("raft_airgap") + self.get_microns("raft_airgap_all")
settings["raftAirGap"] = self.get_microns("raft_airgap_all")
settings["raftBaseSpeed"] = self.get_int("bottom_layer_speed")
settings["raftFanSpeed"] = 100
settings["raftSurfaceThickness"] = settings["raftInterfaceThickness"]
settings["raftSurfaceLinewidth"] = int(edge_width * 1000)
settings["raftSurfaceLineSpacing"] = int(edge_width * 1000 * 0.9)
settings["raftFanSpeed"] = 0
settings["raftSurfaceThickness"] = self.get_microns("raft_surface_thickness")
settings["raftSurfaceLinewidth"] = self.get_microns("raft_surface_linewidth")
settings["raftSurfaceLineSpacing"] = self.get_microns("raft_surface_linewidth")
settings["raftSurfaceLayers"] = self.get_int("raft_surface_layers")
settings["raftSurfaceSpeed"] = self.get_int("bottom_layer_speed")
@@ -8,13 +8,13 @@
{% endtrans %}</p>
<form class="form-horizontal">
{% include "_snippets/settings/cura/enginePath.jinja2" %}
{% include "_snippets/settings/cura/engineLog.jinja2" %}
{% include "snippets/settings/cura/enginePath.jinja2" %}
{% include "snippets/settings/cura/engineLog.jinja2" %}
</form>
<h4>{{ _('Profiles') }}</h4>
{% include "_snippets/settings/cura/profiles.jinja2" %}
{% include "snippets/settings/cura/profiles.jinja2" %}
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
@@ -22,4 +22,4 @@
<small>{% trans %}For more information on configuration and usage please <a href="{{ plugin_cura_homepage }}" target="_blank">see the Plugin's homepage</a>.{% endtrans %}</small>
</div>
{% include "_snippets/settings/cura/profileImporter.jinja2" %}
{% include "snippets/settings/cura/profileImporter.jinja2" %}
@@ -7,7 +7,7 @@
<div style="margin-top: 1em">
<form class="form-horizontal">
{% include "_snippets/settings/cura/enginePath.jinja2" %}
{% include "snippets/settings/cura/enginePath.jinja2" %}
</form>
</div>
</div>
@@ -15,10 +15,11 @@
<div data-bind="visible: unconfiguredSlicingProfile">
<h3>{{ _('Set up a slicing profile') }}</h3>
<p>{% trans %}You haven't imported a slicing profile to use for slicing with CuraEngine
yet. You should do this now.{% endtrans %}</p>
yet. If you plan on slicing from within OctoPrint then you should do this now.
Otherwise just skip this step.{% endtrans %}</p>
<div>
{% include "_snippets/settings/cura/profiles.jinja2" %}
{% include "snippets/settings/cura/profiles.jinja2" %}
</div>
<button class="btn btn-block" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
+26 -10
View File
@@ -34,6 +34,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
pip_inapplicable_arguments = dict(uninstall=["--user"])
def __init__(self):
self._pending_enable = set()
self._pending_disable = set()
@@ -180,6 +182,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if not admin_permission.can():
return make_response("Insufficient rights", 403)
from octoprint.server import safe_mode
refresh_repository = request.values.get("refresh_repository", "false") in valid_boolean_trues
if refresh_repository:
self._repository_available = self._refresh_repository()
@@ -200,7 +204,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
virtual_env=self._pip_caller.virtual_env,
additional_args=self._settings.get(["pip_args"]),
python=sys.executable
))
),
safe_mode=safe_mode)
def etag():
import hashlib
@@ -208,6 +213,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
hash.update(repr(self._get_plugins()))
hash.update(str(self._repository_available))
hash.update(repr(self._repository_plugins))
hash.update(repr(safe_mode))
return hash.hexdigest()
def condition():
@@ -450,7 +456,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
needs_restart_api = needs_restart and not pending
safe_mode_victim = getattr(plugin, "safe_mode_victim", False)
needs_restart_api = (needs_restart or safe_mode_victim) and not pending
needs_refresh_api = needs_refresh and not pending
try:
@@ -482,8 +489,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version")
additional_args = self._settings.get(["pip_args"])
if additional_args:
args.append(additional_args)
if additional_args is not None:
inapplicable_arguments = self.__class__.pip_inapplicable_arguments.get(args[0], list())
for inapplicable_argument in inapplicable_arguments:
additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args)
if additional_args:
args.append(additional_args)
return self._pip_caller.execute(*args)
@@ -514,12 +528,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._settings.global_set(["plugins", "_disabled"], disabled_list)
self._settings.save(force=True)
if not needs_restart:
if not needs_restart and not getattr(plugin, "safe_mode_victim", False):
self._plugin_manager.enable_plugin(plugin.key)
else:
if plugin.key in self._pending_disable:
self._pending_disable.remove(plugin.key)
elif not plugin.enabled and plugin.key not in self._pending_enable:
elif (not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_enable:
self._pending_enable.add(plugin.key)
def _mark_plugin_disabled(self, plugin, needs_restart=False):
@@ -529,12 +543,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._settings.global_set(["plugins", "_disabled"], disabled_list)
self._settings.save(force=True)
if not needs_restart:
if not needs_restart and not getattr(plugin, "safe_mode_victim", False):
self._plugin_manager.disable_plugin(plugin.key)
else:
if plugin.key in self._pending_enable:
self._pending_enable.remove(plugin.key)
elif plugin.enabled and plugin.key not in self._pending_disable:
elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable:
self._pending_disable.add(plugin.key)
def _fetch_repository_from_disk(self):
@@ -688,8 +702,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
bundled=plugin.bundled,
managable=plugin.managable,
enabled=plugin.enabled,
pending_enable=(not plugin.enabled and plugin.key in self._pending_enable),
pending_disable=(plugin.enabled and plugin.key in self._pending_disable),
safe_mode_victim=getattr(plugin, "safe_mode_victim", False),
safe_mode_enabled=getattr(plugin, "safe_mode_enabled", False),
pending_enable=(not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False) and plugin.key in self._pending_enable),
pending_disable=((plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key in self._pending_disable),
pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")),
pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")),
origin=plugin.origin.type
@@ -155,6 +155,8 @@ $(function() {
self.pipAdditionalArgs = ko.observable();
self.pipPython = ko.observable();
self.safeMode = ko.observable();
self.pipUseUserString = ko.pureComputed(function() {
return self.pipUseUser() ? "yes" : "no";
});
@@ -186,7 +188,8 @@ $(function() {
});
self.enableToggle = function(data) {
return self.enableManagement() && data.key != 'pluginmanager';
var command = self._getToggleCommand(data);
return self.enableManagement() && (command == "disable" || !data.safe_mode_victim || data.safe_mode_enabled) && data.key != 'pluginmanager';
};
self.enableUninstall = function(data) {
@@ -199,7 +202,7 @@ $(function() {
};
self.enableRepoInstall = function(data) {
return self.enableManagement() && self.pipAvailable() && self.isCompatible(data);
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data);
};
self.invalidUrl = ko.pureComputed(function() {
@@ -209,7 +212,7 @@ $(function() {
self.enableUrlInstall = ko.pureComputed(function() {
var url = self.installUrl();
return self.enableManagement() && self.pipAvailable() && url !== undefined && url.trim() != "" && !self.invalidUrl();
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl();
});
self.invalidArchive = ko.pureComputed(function() {
@@ -219,7 +222,7 @@ $(function() {
self.enableArchiveInstall = ko.pureComputed(function() {
var name = self.uploadFilename();
return self.enableManagement() && self.pipAvailable() && name !== undefined && name.trim() != "" && !self.invalidArchive();
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && name !== undefined && name.trim() != "" && !self.invalidArchive();
});
self.uploadElement.fileupload({
@@ -246,7 +249,7 @@ $(function() {
done: function(e, data) {
self._markDone();
self.uploadButton.unbind("click");
self.uploadFilename("");
self.uploadFilename(undefined);
},
fail: function(e, data) {
new PNotify({
@@ -257,7 +260,7 @@ $(function() {
});
self._markDone();
self.uploadButton.unbind("click");
self.uploadFilename("");
self.uploadFilename(undefined);
}
});
@@ -278,6 +281,8 @@ $(function() {
self._fromPluginsResponse(data.plugins);
self._fromRepositoryResponse(data.repository);
self._fromPipResponse(data.pip);
self.safeMode(data.safe_mode || false);
};
self._fromPluginsResponse = function(data) {
@@ -347,6 +352,7 @@ $(function() {
};
if (self._getToggleCommand(data) == "enable") {
if (data.safe_mode_victim && !data.safe_mode_enabled) return;
OctoPrint.plugins.pluginmanager.enable(data.key)
.done(onSuccess)
.fail(onError);
@@ -547,7 +553,7 @@ $(function() {
title: titleSuccess,
text: textRestart,
buttons: {
closer: false,
closer: true,
sticker: false
},
callbacks: {
@@ -600,7 +606,7 @@ $(function() {
}]
},
buttons: {
closer: false,
closer: true,
sticker: false
},
callbacks: {
@@ -640,8 +646,9 @@ $(function() {
self.loglines.removeAll();
self.loglines.push({line: line, stream: "message"});
self._scrollWorkingOutputToEnd();
self.workingDialog.modal("show");
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
};
self._markDone = function() {
@@ -655,7 +662,8 @@ $(function() {
};
self._getToggleCommand = function(data) {
return ((!data.enabled || data.pending_disable) && !data.pending_enable) ? "enable" : "disable";
var disable = (data.enabled || data.pending_enable || (data.safe_mode_victim && data.safe_mode_enabled)) && !data.pending_disable;
return disable ? "disable" : "enable";
};
self.toggleButtonCss = function(data) {
@@ -666,7 +674,16 @@ $(function() {
};
self.toggleButtonTitle = function(data) {
return self._getToggleCommand(data) == "enable" ? gettext("Enable Plugin") : gettext("Disable Plugin");
var command = self._getToggleCommand(data);
if (command == "enable") {
if (data.safe_mode_victim && !data.safe_mode_enabled) {
return gettext("Disabled due to active safe mode");
} else {
return gettext("Enable Plugin");
}
} else {
return gettext("Disable Plugin");
}
};
self.onBeforeBinding = function() {
@@ -682,6 +699,10 @@ $(function() {
};
self.onUserLoggedOut = function() {
self._closeAllNotifications();
};
self._closeAllNotifications = function() {
if (self.notifications) {
_.each(self.notifications, function(notification) {
notification.remove();
@@ -689,6 +710,11 @@ $(function() {
}
};
self.onServerDisconnect = function() {
self._closeAllNotifications();
return true;
};
self.onStartup = function() {
self.workingDialog = $("#settings_plugin_pluginmanager_workingdialog");
self.workingOutput = $("#settings_plugin_pluginmanager_workingdialog_output");
@@ -721,7 +747,7 @@ $(function() {
if (messageType == "loglines" && self.working()) {
_.each(data.loglines, function(line) {
self.loglines.push(line);
self.loglines.push(self._preprocessLine(line));
});
self._scrollWorkingOutputToEnd();
} else if (messageType == "result") {
@@ -836,6 +862,14 @@ $(function() {
self.requestData();
}
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._preprocessLine = function(line) {
if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
}
return line;
}
}
// view model class, parameters for constructor, container to bind to
@@ -13,8 +13,16 @@
{% endtrans %}</div>
{% endmacro %}
{% macro pluginmanager_safemode() %}
<div class="alert" data-bind="visible: safeMode">{% trans %}
Safe mode is currently active. All third party plugins are disabled and cannot be
enabled. Installation of plugin packages is disabled.
{% endtrans %}</div>
{% endmacro %}
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }}
<div class="pull-right">
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
@@ -32,7 +40,7 @@
<tbody data-bind="foreach: plugins.paginatedItems">
<tr>
<td class="settings_plugin_plugin_manager_plugins_name">
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i class="icon-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="icon-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="icon-minus" data-bind="visible: pending_uninstall"></i></div>
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i class="icon-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="icon-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="icon-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="icon-medkit" data-bind="visible: safe_mode_victim"></i></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div data-bind="css: {muted: !enabled}">
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
@@ -80,7 +88,6 @@
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
@@ -99,6 +106,7 @@
<div class="modal-body">
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }}
<h4 style="position: relative">
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
<div class="dropdown pull-right">
@@ -794,9 +794,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
try:
util.execute(restart_command)
except exceptions.ScriptError as e:
self._logger.exception("Error while restarting")
self._logger.warn("Restart stdout:\n%s" % e.stdout)
self._logger.warn("Restart stderr:\n%s" % e.stderr)
self._logger.exception("Error while restarting via command {}".format(restart_command))
self._logger.warn("Restart stdout:\n{}".format(e.stdout))
self._logger.warn("Restart stderr:\n{}".format(e.stderr))
raise exceptions.RestartFailed()
def _populated_check(self, target, check):
@@ -882,7 +882,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._send_client_message("loglines", data=dict(loglines=[dict(line=line, stream=stream) for line in lines]))
for line in lines:
self._console_logger.debug(u"{prefix} {line}".format(**locals()))
self._console_logger.debug(u"{} {}".format(prefix, line))
def _send_client_message(self, message_type, data=None):
self._plugin_manager.send_plugin_message(self._identifier, dict(type=message_type, data=data))
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import errno
import sys
import traceback
import time
def _log_call(*lines):
_log(lines, prefix=">", stream="call")
@@ -27,7 +29,9 @@ def _log(lines, prefix=None, stream=None):
output_stream = sys.stderr
for line in lines:
print(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")), file=output_stream)
to_print = _to_str(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")),
errors="replace")
print(to_print, file=output_stream)
def _to_unicode(s_or_u, encoding="utf-8", errors="strict"):
@@ -38,6 +42,14 @@ def _to_unicode(s_or_u, encoding="utf-8", errors="strict"):
return s_or_u
def _to_str(s_or_u, encoding="utf-8", errors="strict"):
"""Make sure ``s_or_u`` is a str."""
if isinstance(s_or_u, unicode):
return s_or_u.encode(encoding, errors=errors)
else:
return s_or_u
def _execute(command, **kwargs):
import sarge
@@ -51,39 +63,54 @@ def _execute(command, **kwargs):
try:
p = sarge.run(command, **kwargs)
p.wait_events()
except Exception as e:
import traceback
exception_lines = traceback.format_exc()
error = "Error while trying to run command {}: {}\n{}".format(joined_command, str(e), exception_lines)
return None, "", error
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
if not p.commands[0].process:
# the process might have been set to None in case of any exception
print("Error while trying to run command {}".format(joined_command), file=sys.stderr)
return None, [], []
except:
print("Error while trying to run command {}".format(joined_command), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
all_stdout = []
all_stderr = []
try:
while p.returncode is None:
while p.commands[0].poll() is None:
lines = p.stderr.readlines(timeout=0.5)
if lines:
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
_log_stderr(*lines)
all_stderr += list(lines)
lines = p.stdout.readlines(timeout=0.5)
if lines:
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
_log_stdout(*lines)
all_stdout += list(lines)
p.commands[0].poll()
finally:
p.close()
lines = p.stderr.readlines()
if lines:
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
_log_stderr(*lines)
all_stderr += lines
lines = p.stdout.readlines()
if lines:
lines = map(lambda x: _to_unicode(x, errors="replace"), lines)
_log_stdout(*lines)
all_stdout += lines
@@ -97,27 +124,31 @@ def _get_git_executables():
return GITS
def _git(args, cwd, verbose=False, git_executable=None):
def _git(args, cwd, git_executable=None):
if git_executable is not None:
commands = [git_executable]
else:
commands = _get_git_executables()
for c in commands:
command = [c] + args
try:
return _execute([c] + args, cwd=cwd)
return _execute(command, cwd=cwd)
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % args[0])
print(e)
return None, None, None
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
except:
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
return None, None, None
print("Unable to find git command, tried {}".format(", ".join(commands)), file=sys.stderr)
return None, [], []
def _python(args, cwd, python_executable, sudo=False):
@@ -127,31 +158,40 @@ def _python(args, cwd, python_executable, sudo=False):
try:
return _execute(command, cwd=cwd)
except:
return None, None, None
import traceback
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
def _to_error(*lines):
return u"".join(map(lambda x: _to_unicode(x, errors="replace"), lines))
if len(lines) == 1:
if isinstance(lines[0], (list, tuple)):
lines = lines[0]
elif not isinstance(lines[0], (str, unicode)):
lines = [repr(lines[0]),]
return u"\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines))
def _rescue_changes(git_executable, folder):
print(">>> Running: git diff --shortstat")
returncode, stdout, stderr = _git(["diff", "--shortstat"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git diff\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
if stdout and "".join(stdout).strip():
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git diff\" failed with returncode {}".format(returncode))
if stdout and u"".join(stdout).strip():
# we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch
import time
import os
timestamp = time.strftime("%Y%m%d%H%M")
patch = os.path.join(folder, "%s-preupdate.patch" % timestamp)
patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp))
print(">>> Running: git diff and saving output to %s" % timestamp)
print(">>> Running: git diff and saving output to {}".format(patch))
returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, installation directory was dirty and state could not be persisted as a patch to %s" % patch)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, installation directory was dirty and state could not be persisted as a patch to {}".format(patch))
with open(patch, "wb") as f:
import codecs
with codecs.open(patch, "w", encoding="utf-8", errors="replace") as f:
for line in stdout:
f.write(line)
@@ -164,46 +204,45 @@ def update_source(git_executable, folder, target, force=False, branch=None):
if _rescue_changes(git_executable, folder):
print(">>> Running: git reset --hard")
returncode, stdout, stderr = _git(["reset", "--hard"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode {}".format(returncode))
print(">>> Running: git clean -f -d -e *-preupdate.patch")
returncode, stdout, stderr = _git(["clean", "-f", "-d", "-e", "*-preupdate.patch"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git clean -f\" failed with returcode %d: %s" % (returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git clean -f\" failed with returncode {}".format(returncode))
print(">>> Running: git fetch")
returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git fetch\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
print(stdout)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git fetch\" failed with returncode {}".format(returncode))
if branch is not None and branch.strip() != "":
print(">>> Running: git checkout {}".format(branch))
returncode, stdout, stderr = _git(["checkout", branch], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git checkout\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git checkout\" failed with returncode {}".format(returncode))
print(">>> Running: git pull")
returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git pull\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git pull\" failed with returncode {}".format(returncode))
if force:
reset_command = ["reset", "--hard"]
reset_command += [target]
print(">>> Running: git %s" % " ".join(reset_command))
print(">>> Running: git {}".format(" ".join(reset_command)))
returncode, stdout, stderr = _git(reset_command, folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Error while updating, \"git %s\" failed with returncode %d: %s" % (" ".join(reset_command), returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Error while updating, \"git {}\" failed with returncode {}".format(" ".join(reset_command), returncode))
def install_source(python_executable, folder, user=False, sudo=False):
print(">>> Running: python setup.py clean")
returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable)
if returncode != 0:
print("\"python setup.py clean\" failed with returncode %d: %s" % (returncode, stdout))
if returncode is None or returncode != 0:
print("\"python setup.py clean\" failed with returncode {}".format(returncode))
print("Continuing anyways")
print(">>> Running: python setup.py install")
@@ -211,15 +250,14 @@ def install_source(python_executable, folder, user=False, sudo=False):
if user:
args.append("--user")
returncode, stdout, stderr = _python(args, folder, python_executable, sudo=sudo)
if returncode != 0:
raise RuntimeError("Could not update, \"python setup.py install\" failed with returncode %d: %s" % (returncode, _to_error(*stdout)))
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"python setup.py install\" failed with returncode {}".format(returncode))
def parse_arguments():
import argparse
boolean_trues = ["true", "yes", "1"]
boolean_falses = ["false", "no", "0"]
parser = argparse.ArgumentParser(prog="update-octoprint.py")
@@ -103,6 +103,8 @@ $(function() {
self.workingOutput = undefined;
self.loglines = ko.observableArray([]);
self.checking = ko.observable(false);
self.octoprintUnconfigured = ko.observable();
self.octoprintUnreleased = ko.observable();
@@ -333,7 +335,7 @@ $(function() {
};
}
if (ignoreSeen || !self._hasNotificationBeenSeen(data.information)) {
if ((ignoreSeen || !self._hasNotificationBeenSeen(data.information)) && !OctoPrint.coreui.wizardOpen) {
self._showPopup(options, eventListeners);
}
} else if (data.status == "current") {
@@ -351,9 +353,13 @@ $(function() {
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
if (!self.loginState.isUser()) return;
self.checking(true);
OctoPrint.plugins.softwareupdate.check(force)
.done(function(data) {
self.fromCheckResponse(data, ignoreSeen, showIfNothingNew);
})
.always(function() {
self.checking(false);
});
};
@@ -454,7 +460,7 @@ $(function() {
self.working(true);
self.workingTitle(title);
self.workingDialog.modal("show");
self.workingDialog.modal({keyboard: false, backdrop: "static", show: true});
};
self._markWorking = function(title, line, stream) {
@@ -482,7 +488,7 @@ $(function() {
self.workingOutput.scrollTop(self.workingOutput[0].scrollHeight - self.workingOutput.height());
};
self.onWizardTabChange = function(current, next) {
self.onBeforeWizardTabChange = function(next, current) {
if (next && _.startsWith(next, "wizard_plugin_softwareupdate")) {
// switching to the plugin wizard tab
self._copyConfig();
@@ -539,7 +545,7 @@ $(function() {
case "loglines": {
if (self.working()) {
_.each(messageData.loglines, function(line) {
self.loglines.push(line);
self.loglines.push(self._preprocessLine(line));
});
self._scrollWorkingOutputToEnd();
}
@@ -557,6 +563,7 @@ $(function() {
self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
self.loglines.push({line: text, stream: "message"});
self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
self._scrollWorkingOutputToEnd();
self._updatePopup({
text: text,
hide: false,
@@ -584,6 +591,7 @@ $(function() {
};
self.loglines.push({line: text, stream: "message"});
self._scrollWorkingOutputToEnd();
self.waitingForRestart = true;
self.restartTimeout = setTimeout(function() {
@@ -694,6 +702,13 @@ $(function() {
}
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._preprocessLine = function(line) {
if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
}
return line;
}
}
// view model class, parameters for constructor, container to bind to
@@ -57,12 +57,12 @@
</ul>
</div>
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }">{{ _('Check for update now') }}</button>
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="icon-spinner icon-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
<div>
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }">{{ _('Force check for update (overrides cache used for update checks)') }}</button>
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="icon-spinner icon-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
</div>
</div>
@@ -74,9 +74,9 @@
</div>
<div class="modal-body">
<form class="form-horizontal">
{% include "_snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
{% include "_snippets/plugins/softwareupdate/versionTracking.jinja2" %}
{% include "_snippets/plugins/softwareupdate/releaseChannel.jinja2" %}
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
{% include "snippets/plugins/softwareupdate/versionTracking.jinja2" %}
{% include "snippets/plugins/softwareupdate/releaseChannel.jinja2" %}
<div class="control-group">
<label class="control-label">{{ _('Version cache TTL') }}</label>
<div class="controls">
@@ -96,7 +96,6 @@
<div id="settings_plugin_softwareupdate_workingdialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
@@ -6,8 +6,8 @@
</p>{% endtrans %}
<form class="form-horizontal">
{% include "_snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
{% include "_snippets/plugins/softwareupdate/versionTracking.jinja2" %}
{% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %}
{% include "snippets/plugins/softwareupdate/versionTracking.jinja2" %}
</form>
{% trans %}<p>
@@ -28,6 +28,7 @@ def _filter_out_latest(releases,
>>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance")
>>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> release_1_2_18 = dict(name="1.2.18", tag_name="1.2.18", html_url="some_url", published_at="2016-12-13T12:00:00Z", prerelease=False, draft=False, target_commitish="master")
>>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future")
>>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1]
>>> _filter_out_latest(releases, include_prerelease=False, prerelease_channel=None)
@@ -44,6 +45,14 @@ def _filter_out_latest(releases,
(None, None, None)
>>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2])
(None, None, None)
>>> comparable_factory = _get_comparable_factory("python", force_base=True)
>>> sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, prerelease_channel=None, sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/maintenance", sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/devel", sort_key=sort_key)
('1.3.0rc1', '1.3.0rc1', 'some_url')
"""
nothing = None, None, None
@@ -59,15 +59,17 @@ class VirtualPrinter(object):
self.lastTempAt = time.time()
self.bedTemp = 1.0
self.bedTargetTemp = 1.0
self.speeds = settings().get(["devel", "virtualPrinter", "movementSpeed"])
self._relative = True
self._lastX = None
self._lastY = None
self._lastZ = None
self._lastE = None
self._lastX = 0.0
self._lastY = 0.0
self._lastZ = 0.0
self._lastE = 0.0
self._lastF = 200
self._unitModifier = 1
self._feedrate_multiplier = 100
self._flowrate_multiplier = 100
self._virtualSd = settings().getBaseFolder("virtualSd")
self._sdCardReady = True
@@ -92,6 +94,8 @@ class VirtualPrinter(object):
self._brokenM29 = settings().getBoolean(["devel", "virtualPrinter", "brokenM29"])
self._firmwareName = settings().get(["devel", "virtualPrinter", "firmwareName"])
self.currentLine = 0
self.lastN = 0
@@ -317,7 +321,7 @@ class VirtualPrinter(object):
def _gcode_M140(self, data):
self._parseBedCommand(data)
def _gcode_M140(self, data):
def _gcode_M190(self, data):
self._parseBedCommand(data, wait=True, support_r=True)
def _gcode_M105(self, data):
@@ -372,17 +376,27 @@ class VirtualPrinter(object):
self._deleteSdFile(filename)
def _gcode_M114(self, data):
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE, int(self._lastX*100), int(self.lastY*100), int(self.lastZ*100))
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE, int(self._lastX*100), int(self._lastY*100), int(self._lastZ*100))
if not self._okBeforeCommandOutput:
output = "ok " + output
self._send(output)
return True
def _gcode_M115(self, data):
output = "FIRMWARE_NAME:{} PROTOCOL_VERSION:1.0".format(self._firmwareName)
self._send(output)
def _gcode_M117(self, data):
# we'll just use this to echo a message, to allow playing around with pause triggers
if self._echoOnM117:
self._send("echo:%s" % re.search("M117\s+(.*)", data).group(1))
def _gcode_M220(self, data):
self._feedrate_multiplier = float(re.search('S([0-9]+)', data).group(1))
def _gcode_M221(self, data):
self._flowrate_multiplier = float(re.search('S([0-9]+)', data).group(1))
def _gcode_M400(self, data):
self.buffered.join()
@@ -631,16 +645,18 @@ class VirtualPrinter(object):
if settings().getBoolean(["devel", "virtualPrinter", "includeCurrentToolInTemps"]):
if includeTarget:
output = "T:%.2f /%.2f %s @:64\n" % (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder] + 1, allTempsString)
output = "T:%.2f /%.2f %s" % (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder] + 1, allTempsString)
else:
output = "T:%.2f %s @:64\n" % (self.temp[self.currentExtruder], allTempsString)
output = "T:%.2f %s" % (self.temp[self.currentExtruder], allTempsString)
else:
output = "%s @:64\n" % allTempsString
output = allTempsString
else:
if includeTarget:
output = "T:%.2f /%.2f B:%.2f /%.2f @:64\n" % (self.temp[0], self.targetTemp[0], self.bedTemp, self.bedTargetTemp)
output = "T:%.2f /%.2f B:%.2f /%.2f" % (self.temp[0], self.targetTemp[0], self.bedTemp, self.bedTargetTemp)
else:
output = "T:%.2f B:%.2f @:64\n" % (self.temp[0], self.bedTemp)
output = "T:%.2f B:%.2f" % (self.temp[0], self.bedTemp)
output += " @:64\n"
if includeOk:
output = "ok " + output
@@ -696,46 +712,72 @@ class VirtualPrinter(object):
matchY = re.search("Y([0-9.]+)", line)
matchZ = re.search("Z([0-9.]+)", line)
matchE = re.search("E([0-9.]+)", line)
matchF = re.search("F([0-9.]+)", line)
duration = 0
if matchF is not None:
try:
self._lastF = float(matchF.group(1))
except:
pass
speedXYZ = self._lastF * (self._feedrate_multiplier / 100.0)
speedE = self._lastF * (self._flowrate_multiplier / 100.0)
if matchX is not None:
try:
x = float(matchX.group(1))
if self._relative or self._lastX is None:
duration = max(duration, x * self._unitModifier / float(self.speeds["x"]) * 60.0)
duration = max(duration, x * self._unitModifier / speedXYZ * 60.0)
else:
duration = max(duration, (x - self._lastX) * self._unitModifier / float(self.speeds["x"]) * 60.0)
self._lastX = x
duration = max(duration, (x - self._lastX) * self._unitModifier / speedXYZ * 60.0)
if self._relative and self._lastX is not None:
self._lastX += x
else:
self._lastX = x
except:
pass
if matchY is not None:
try:
y = float(matchY.group(1))
if self._relative or self._lastY is None:
duration = max(duration, y * self._unitModifier / float(self.speeds["y"]) * 60.0)
duration = max(duration, y * self._unitModifier / speedXYZ * 60.0)
else:
duration = max(duration, (y - self._lastY) * self._unitModifier / float(self.speeds["y"]) * 60.0)
self._lastY = y
duration = max(duration, (y - self._lastY) * self._unitModifier / speedXYZ * 60.0)
if self._relative and self._lastY is not None:
self._lastY += y
else:
self._lastY = y
except:
pass
if matchZ is not None:
try:
z = float(matchZ.group(1))
if self._relative or self._lastZ is None:
duration = max(duration, z * self._unitModifier / float(self.speeds["z"]) * 60.0)
duration = max(duration, z * self._unitModifier / speedXYZ * 60.0)
else:
duration = max(duration, (z - self._lastZ) * self._unitModifier / float(self.speeds["z"]) * 60.0)
self._lastZ = z
duration = max(duration, (z - self._lastZ) * self._unitModifier / speedXYZ * 60.0)
if self._relative and self._lastZ is not None:
self._lastZ += z
else:
self._lastZ = z
except:
pass
if matchE is not None:
try:
e = float(matchE.group(1))
if self._relative or self._lastE is None:
duration = max(duration, e * self._unitModifier / float(self.speeds["e"]) * 60.0)
duration = max(duration, e * self._unitModifier / speedE * 60.0)
else:
duration = max(duration, (e - self._lastE) * self._unitModifier / float(self.speeds["e"]) * 60.0)
self._lastE = e
duration = max(duration, (e - self._lastE) * self._unitModifier / speedE * 60.0)
if self._relative and self._lastE is not None:
self._lastE += e
else:
self._lastE = e
except:
pass
+81 -5
View File
@@ -34,7 +34,7 @@ class BedTypes(object):
@classmethod
def values(cls):
return [getattr(cls, name) for name in cls.__dict__ if not name.startswith("__")]
return [getattr(cls, name) for name in cls.__dict__ if not (name.startswith("__") or name == "values")]
class BedOrigin(object):
LOWERLEFT = "lowerleft"
@@ -42,7 +42,7 @@ class BedOrigin(object):
@classmethod
def values(cls):
return [getattr(cls, name) for name in cls.__dict__ if not name.startswith("__")]
return [getattr(cls, name) for name in cls.__dict__ if not (name.startswith("__") or name == "values")]
class PrinterProfileManager(object):
"""
@@ -88,6 +88,28 @@ class PrinterProfileManager(object):
* - ``volume.origin``
- ``string``
- Location of gcode origin in the print volume, either ``lowerleft`` or ``center``
* - ``volume.custom_box``
- ``dict`` or ``False``
- Custom boundary box overriding the default bounding box based on the provided width, depth, height and origin.
If ``False``, the default boundary box will be used.
* - ``volume.custom_box.x_min``
- ``float``
- Minimum valid X coordinate
* - ``volume.custom_box.y_min``
- ``float``
- Minimum valid Y coordinate
* - ``volume.custom_box.z_min``
- ``float``
- Minimum valid Z coordinate
* - ``volume.custom_box.x_max``
- ``float``
- Maximum valid X coordinate
* - ``volume.custom_box.y_max``
- ``float``
- Maximum valid Y coordinate
* - ``volume.custom_box.z_max``
- ``float``
- Maximum valid Z coordinate
* - ``heatedBed``
- ``bool``
- Whether the printer has a heated bed (``True``) or not (``False``)
@@ -154,7 +176,8 @@ class PrinterProfileManager(object):
depth = 200,
height = 200,
formFactor = BedTypes.RECTANGULAR,
origin = BedOrigin.LOWERLEFT
origin = BedOrigin.LOWERLEFT,
custom_box = False
),
heatedBed = True,
extruder=dict(
@@ -391,11 +414,17 @@ class PrinterProfileManager(object):
def _migrate_profile(self, profile):
# make sure profile format is up to date
modified = False
if "volume" in profile and "formFactor" in profile["volume"] and not "origin" in profile["volume"]:
profile["volume"]["origin"] = BedOrigin.CENTER if profile["volume"]["formFactor"] == BedTypes.CIRCULAR else BedOrigin.LOWERLEFT
return True
modified = True
return False
if "volume" in profile and not "custom_box" in profile["volume"]:
profile["volume"]["custom_box"] = False
modified = True
return modified
def _ensure_valid_profile(self, profile):
# ensure all keys are present
@@ -458,6 +487,35 @@ class PrinterProfileManager(object):
if profile["volume"]["formFactor"] == BedTypes.CIRCULAR:
profile["volume"]["depth"] = profile["volume"]["width"]
# if we have a custom bounding box, validate it
if profile["volume"]["custom_box"] and isinstance(profile["volume"]["custom_box"], dict):
if not len(profile["volume"]["custom_box"]):
profile["volume"]["custom_box"] = False
else:
default_box = self._default_box_for_volume(profile["volume"])
for prop, limiter in (("x_min", min), ("y_min", min), ("z_min", min),
("x_max", max), ("y_max", max), ("z_max", max)):
if prop not in profile["volume"]["custom_box"] or profile["volume"]["custom_box"][prop] is None:
profile["volume"]["custom_box"][prop] = default_box[prop]
else:
value = profile["volume"]["custom_box"][prop]
try:
value = limiter(float(value), default_box[prop])
profile["volume"]["custom_box"][prop] = value
except:
self._logger.warn("Profile has invalid value in volume.custom_box.{}: {!r}".format(prop, value))
return False
# make sure we actually do have a custom box and not just the same values as the
# default box
for prop in profile["volume"]["custom_box"]:
if profile["volume"]["custom_box"][prop] != default_box[prop]:
break
else:
# exactly the same as the default box, remove custom box
profile["volume"]["custom_box"] = False
# validate offsets
offsets = []
for offset in profile["extruder"]["offsets"]:
@@ -474,3 +532,21 @@ class PrinterProfileManager(object):
return profile
@staticmethod
def _default_box_for_volume(volume):
if volume["origin"] == BedOrigin.CENTER:
half_width = volume["width"] / 2.0
half_depth = volume["depth"] / 2.0
return dict(x_min=-half_width,
x_max=half_width,
y_min=-half_depth,
y_max=half_depth,
z_min=0.0,
z_max=volume["height"])
else:
return dict(x_min=0.0,
x_max=volume["width"],
y_min=0.0,
y_max=volume["depth"],
z_min=0.0,
z_max=volume["height"])
+32 -18
View File
@@ -168,7 +168,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
#~~ progress plugin reporting
def _reportPrintProgressToPlugins(self, progress):
if not progress or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile:
if progress is None or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile:
return
storage = "sdcard" if self._selectedFile["sd"] else "local"
@@ -393,7 +393,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._printAfterSelect = printAfterSelect
self._posAfterSelect = pos
self._comm.selectFile("/" + path if sd and not settings().getBoolean(["feature", "sdRelativePath"]) else path, sd)
self._comm.selectFile("/" + path if sd else path, sd)
self._setProgressData(completion=0)
self._setCurrentZ(None)
@@ -405,6 +405,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setProgressData(completion=0)
self._setCurrentZ(None)
def get_file_position(self):
if self._comm is None:
return None
if self._selectedFile is None:
return None
return self._comm.getFilePosition()
def start_print(self, pos=None):
"""
Starts the currently loaded print job.
@@ -478,12 +487,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# mark print as failure
if self._selectedFile is not None:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
payload = {
"file": self._selectedFile["filename"],
"origin": FileDestinations.LOCAL
}
if self._selectedFile["sd"]:
payload["origin"] = FileDestinations.SDCARD
payload = self._payload_for_print_job_event()
eventManager().fire(Events.PRINT_FAILED, payload)
def get_state_string(self, state=None):
@@ -754,7 +758,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"""
if progress is None or printTime is None or cleanedPrintTime is None:
return None
return None, None
dumbTotalPrintTime = printTime / progress
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
@@ -956,6 +960,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
def on_comm_temperature_update(self, temp, bedTemp):
self._addTemperatureData(copy.deepcopy(temp), copy.deepcopy(bedTemp))
def on_comm_position_update(self, position, reason=None):
payload = dict(reason=reason)
payload.update(position)
eventManager().fire(Events.POSITION_UPDATE, payload)
def on_comm_state_change(self, state):
"""
Callback method for the comm object, called if the connection state changes.
@@ -1063,7 +1072,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
eventManager().fire(Events.PRINT_FAILED, payload)
def on_comm_print_job_cancelled(self):
payload = self._payload_for_print_job_event()
payload = self._payload_for_print_job_event(position=self._comm.cancel_position.as_dict() if self._comm and self._comm.cancel_position else None)
if payload:
eventManager().fire(Events.PRINT_CANCELLED, payload)
self.script("afterPrintCancelled",
@@ -1071,7 +1080,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
must_be_set=False)
def on_comm_print_job_paused(self):
payload = self._payload_for_print_job_event()
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None)
if payload:
eventManager().fire(Events.PRINT_PAUSED, payload)
self.script("afterPrintPaused",
@@ -1117,7 +1126,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
except:
self._logger.exception("Error while trying to persist print recovery data")
def _payload_for_print_job_event(self, location=None, print_job_file=None):
def _payload_for_print_job_event(self, location=None, print_job_file=None, position=None):
if print_job_file is None:
selected_file = self._selectedFile
if not selected_file:
@@ -1142,13 +1151,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
_, name = self._fileManager.split_path(FileDestinations.LOCAL, path)
origin = FileDestinations.LOCAL
return dict(name=name,
path=path,
origin=origin,
result= dict(name=name,
path=path,
origin=origin,
# TODO deprecated, remove in 1.4.0
file=full_path,
filename=name)
# TODO deprecated, remove in 1.4.0
file=full_path,
filename=name)
if position is not None:
result["position"] = position
return result
class StateMonitor(object):
+23 -3
View File
@@ -33,6 +33,7 @@ app = Flask("octoprint")
assets = None
babel = None
debug = False
safe_mode = False
printer = None
printerProfileManager = None
@@ -112,12 +113,13 @@ def load_user(id):
class Server(object):
def __init__(self, settings=None, plugin_manager=None, host="0.0.0.0", port=5000, debug=False, allow_root=False, octoprint_daemon=None):
def __init__(self, settings=None, plugin_manager=None, host="0.0.0.0", port=5000, debug=False, safe_mode=False, allow_root=False, octoprint_daemon=None):
self._settings = settings
self._plugin_manager = plugin_manager
self._host = host
self._port = port
self._debug = debug
self._safe_mode = safe_mode
self._allow_root = allow_root
self._octoprint_daemon = octoprint_daemon
self._server = None
@@ -155,11 +157,13 @@ class Server(object):
global pluginLifecycleManager
global preemptiveCache
global debug
global safe_mode
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
debug = self._debug
safe_mode = self._safe_mode
self._logger = logging.getLogger(__name__)
pluginManager = self._plugin_manager
@@ -245,7 +249,14 @@ class Server(object):
return props
def settings_plugin_inject_factory(name, implementation):
"""Factory for additional injections depending on plugin type"""
"""Factory for additional injections/initializations depending on plugin type"""
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
return
default_settings_overlay = dict(plugins=dict())
default_settings_overlay["plugins"][name] = implementation.get_settings_defaults()
self._settings.add_overlay(default_settings_overlay, at_end=True)
plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin(name, implementation)
if plugin_settings is None:
return
@@ -272,7 +283,8 @@ class Server(object):
implementation.on_settings_initialized()
pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory, settings_plugin_inject_factory]
pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory,
settings_plugin_inject_factory]
pluginManager.initialize_implementations()
settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin)
@@ -487,6 +499,11 @@ class Server(object):
def on_after_startup():
self._logger.info("Listening on http://%s:%d" % (self._host, self._port))
if safe_mode and self._settings.getBoolean(["server", "startOnceInSafeMode"]):
self._logger.info("Server started successfully in safe mode as requested from config, removing flag")
self._settings.setBoolean(["server", "startOnceInSafeMode"], False)
self._settings.save()
# now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for
# which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons
# or service xmls or the like). While they are working though the ioloop would block. Therefore we'll
@@ -567,6 +584,9 @@ class Server(object):
if "l10n" in request.values:
return Locale.negotiate([request.values["l10n"]], LANGUAGES)
if "X-Locale" in request.headers:
return Locale.negotiate([request.headers["X-Locale"]], LANGUAGES)
if hasattr(g, "identity") and g.identity and userManager.enabled:
userid = g.identity.id
try:
+8 -8
View File
@@ -248,8 +248,8 @@ def _verifyFolderExists(origin, foldername):
def _isBusy(target, path):
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename is not None and currentOrigin == target and fileManager.file_in_path(FileDestinations.LOCAL, path, currentFilename) and (printer.is_printing() or printer.is_paused()):
currentOrigin, currentPath = _getCurrentFile()
if currentPath is not None and currentOrigin == target and fileManager.file_in_path(FileDestinations.LOCAL, path, currentPath) and (printer.is_printing() or printer.is_paused()):
return True
return any(target == x[0] and fileManager.file_in_path(FileDestinations.LOCAL, path, x[1]) for x in fileManager.get_busy_files())
@@ -705,8 +705,8 @@ def deleteGcodeFile(filename, target):
return make_response("Trying to delete a file that is currently in use: %s" % filename, 409)
# deselect the file if it's currently selected
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename is not None and currentOrigin == target and filename == currentFilename:
currentOrigin, currentPath = _getCurrentFile()
if currentPath is not None and currentOrigin == target and filename == currentPath:
printer.unselect_file()
# delete it
@@ -723,8 +723,8 @@ def deleteGcodeFile(filename, target):
return make_response("Trying to delete a folder that contains a file that is currently in use: %s" % filename, 409)
# deselect the file if it's currently selected
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename is not None and currentOrigin == target and fileManager.file_in_path(target, filename, currentFilename):
currentOrigin, currentPath = _getCurrentFile()
if currentPath is not None and currentOrigin == target and fileManager.file_in_path(target, filename, currentPath):
printer.unselect_file()
# delete it
@@ -734,8 +734,8 @@ def deleteGcodeFile(filename, target):
def _getCurrentFile():
currentJob = printer.get_current_job()
if currentJob is not None and "file" in currentJob.keys() and "name" in currentJob["file"] and "origin" in currentJob["file"]:
return currentJob["file"]["origin"], currentJob["file"]["name"]
if currentJob is not None and "file" in currentJob.keys() and "path" in currentJob["file"] and "origin" in currentJob["file"]:
return currentJob["file"]["origin"], currentJob["file"]["path"]
else:
return None, None
+5 -4
View File
@@ -31,6 +31,7 @@ def _etag(lm=None):
hash = hashlib.sha1()
hash.update(str(lm))
hash.update(repr(printerProfileManager.get_default()))
hash.update(repr(printerProfileManager.get_current()))
return hash.hexdigest()
@@ -128,17 +129,17 @@ def printerProfilesUpdate(identifier):
profile = printerProfileManager.get_default()
new_profile = json_data["profile"]
new_profile = dict_merge(profile, new_profile)
merged_profile = dict_merge(profile, new_profile)
make_default = False
if "default" in new_profile:
if "default" in merged_profile:
make_default = True
del new_profile["default"]
new_profile["id"] = identifier
merged_profile["id"] = identifier
try:
saved_profile = printerProfileManager.save(new_profile, allow_overwrite=True, make_default=make_default)
saved_profile = printerProfileManager.save(merged_profile, allow_overwrite=True, make_default=make_default)
except InvalidProfileError:
return make_response("Profile is invalid", 400)
except CouldNotOverwriteError:
+65 -18
View File
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
from flask import request, jsonify, make_response
from flask.ext.login import current_user
from werkzeug.exceptions import BadRequest
from octoprint.events import eventManager, Events
@@ -30,11 +31,41 @@ def _etag(lm=None):
lm = _lastmodified()
connection_options = printer.__class__.get_connection_options()
plugins = sorted(octoprint.plugin.plugin_manager().enabled_plugins)
plugin_settings = _get_plugin_settings()
from collections import OrderedDict
sorted_plugin_settings = OrderedDict()
for key in sorted(plugin_settings.keys()):
sorted_plugin_settings[key] = plugin_settings.get(key, dict())
if current_user is not None and not current_user.is_anonymous():
roles = sorted(current_user.roles)
else:
roles = []
import hashlib
hash = hashlib.sha1()
# last modified timestamp
hash.update(str(lm))
# effective config from config.yaml + overlays
hash.update(repr(settings().effective))
# might duplicate settings().effective, but plugins might also inject additional keys into the settings
# output that are not stored in config.yaml
hash.update(repr(sorted_plugin_settings))
# connection options are also part of the settings
hash.update(repr(connection_options))
# if the list of plugins changes, the settings structure changes too
hash.update(repr(plugins))
# and likewise if the role of the user changes
hash.update(repr(roles))
return hash.hexdigest()
@api.route("/settings", methods=["GET"])
@@ -42,8 +73,6 @@ def _etag(lm=None):
lastmodified_factory=_lastmodified,
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
def getSettings():
logger = logging.getLogger(__name__)
s = settings()
connectionOptions = printer.__class__.get_connection_options()
@@ -95,7 +124,9 @@ def getSettings():
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"]),
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"])
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
"firmwareDetection": s.getBoolean(["feature", "firmwareDetection"]),
"printCancelConfirmation": s.getBoolean(["feature", "printCancelConfirmation"])
},
"serial": {
"port": connectionOptions["portPreference"],
@@ -170,32 +201,45 @@ def getSettings():
for name in gcode_scripts:
data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True)
plugin_settings = _get_plugin_settings()
if len(plugin_settings):
data["plugins"] = plugin_settings
return jsonify(data)
def _get_plugin_settings():
logger = logging.getLogger(__name__)
data = dict()
def process_plugin_result(name, result):
if result:
try:
jsonify(test=result)
except:
logger.exception("Error while jsonifying settings from plugin {}, please contact the plugin author about this".format(name))
if not "plugins" in data:
data["plugins"] = dict()
if "__enabled" in result:
del result["__enabled"]
data["plugins"][name] = result
raise
else:
if "__enabled" in result:
del result["__enabled"]
data[name] = result
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
try:
result = plugin.on_settings_load()
process_plugin_result(plugin._identifier, result)
except TypeError:
logger.warn("Could not load settings for plugin {name} ({version}) since it called super(...)".format(name=plugin._plugin_name, version=plugin._plugin_version))
logger.warn("Could not load settings for plugin {name} ({version}) since it called super(...)".format(name=plugin._plugin_name,
version=plugin._plugin_version))
logger.warn("in a way which has issues due to OctoPrint's dynamic reloading after plugin operations.")
logger.warn("Please contact the plugin's author and ask to update the plugin to use a direct call like")
logger.warn("octoprint.plugin.SettingsPlugin.on_settings_load(self) instead.")
except:
logger.exception("Could not load settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name))
logger.exception("Could not load settings for plugin {name} ({version})".format(version=plugin._plugin_version,
name=plugin._plugin_name))
return jsonify(data)
return data
@api.route("/settings", methods=["POST"])
@@ -265,6 +309,8 @@ def _saveSettings(data):
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"])
if "firmwareDetection" in data["feature"]: s.setBoolean(["feature", "firmwareDetection"], data["feature"]["firmwareDetection"])
if "printCancelConfirmation" in data["feature"]: s.setBoolean(["feature", "printCancelConfirmation"], data["feature"]["printCancelConfirmation"])
if "serial" in data.keys():
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
@@ -348,9 +394,10 @@ def _saveSettings(data):
except:
logger.exception("Could not save settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name))
if s.save():
payload = dict(
config_hash=s.config_hash,
effective_hash=s.effective_hash
)
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
s.save()
payload = dict(
config_hash=s.config_hash,
effective_hash=s.effective_hash
)
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
+5 -5
View File
@@ -129,19 +129,19 @@ def _get_core_command_specs():
commands = collections.OrderedDict(
shutdown=dict(
command=s().get(["server", "commands", "systemShutdownCommand"]),
name=gettext("Shutdown"),
name=gettext("Shutdown system"),
confirm=gettext("You are about to shutdown the system.")),
reboot=dict(
command=s().get(["server", "commands", "systemRestartCommand"]),
name=gettext("Reboot"),
name=gettext("Reboot system"),
confirm=gettext("You are about to reboot the system.")),
restart=dict(
command=s().get(["server", "commands", "serverRestartCommand"]),
name="Restart OctoPrint",
confirm="You are about to restart the OctoPrint server.")
name=gettext("Restart OctoPrint"),
confirm=gettext("You are about to restart the OctoPrint server."))
)
available_commands = dict()
available_commands = collections.OrderedDict()
for action, spec in commands.items():
if not spec["command"]:
continue
+34 -17
View File
@@ -30,6 +30,21 @@ _timelapse_cache_unrendered = []
_timelapse_cache_unrendered_lastmodified = None
_timelapse_cache_mutex = threading.RLock()
def _config_for_timelapse(timelapse):
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
return dict(type="zchange",
postRoll=timelapse.post_roll,
fps=timelapse.fps,
retractionZHop=timelapse.retraction_zhop)
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
return dict(type="timed",
postRoll=timelapse.post_roll,
fps=timelapse.fps,
interval=timelapse.interval,
capturePostRoll=timelapse.capture_post_roll)
else:
return dict(type="off")
def _lastmodified(unrendered):
lm_finished = octoprint.timelapse.last_modified_finished()
if unrendered:
@@ -44,9 +59,13 @@ def _etag(unrendered, lm=None):
if lm is None:
lm = _lastmodified(unrendered)
timelapse = octoprint.timelapse.current
config = _config_for_timelapse(timelapse)
import hashlib
hash = hashlib.sha1()
hash.update(str(lm))
hash.update(repr(config))
return hash.hexdigest()
@@ -56,19 +75,7 @@ def _etag(unrendered, lm=None):
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
def getTimelapseData():
timelapse = octoprint.timelapse.current
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
config = dict(type="zchange",
postRoll=timelapse.post_roll,
fps=timelapse.fps,
retractionZHop=timelapse.retraction_zhop)
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
config = dict(type="timed",
postRoll=timelapse.post_roll,
fps=timelapse.fps,
interval=timelapse.interval)
else:
config = dict(type="off")
config = _config_for_timelapse(timelapse)
force = request.values.get("force", "false") in valid_boolean_trues
unrendered = request.values.get("unrendered", "false") in valid_boolean_trues
@@ -204,21 +211,31 @@ def setTimelapseConfig():
else:
return make_response("Invalid value for interval: %d" % interval)
if "retractionZHop" in request.values:
if "capturePostRoll" in data:
config["options"]["capturePostRoll"] = True
try:
capturePostRoll = bool(data["capturePostRoll"])
except ValueError:
return make_response("Invalid value for capturePostRoll: %r" % data["capturePostRoll"])
else:
config["options"]["capturePostRoll"] = capturePostRoll
if "retractionZHop" in data:
config["options"] = {
"retractionZHop": 0
}
try:
retractionZHop = float(request.values["retractionZHop"])
retractionZHop = float(data["retractionZHop"])
except ValueError:
return make_response("Invalid value for retraction Z-Hop: %r" % request.values["retractionZHop"])
return make_response("Invalid value for retraction Z-Hop: %r" % data["retractionZHop"])
else:
if retractionZHop > 0:
if retractionZHop >= 0:
config["options"]["retractionZHop"] = retractionZHop
else:
return make_response("Invalid value for retraction Z-Hop: %d" % retractionZHop)
if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues:
octoprint.timelapse.configure_timelapse(config, True)
else:
+50 -3
View File
@@ -236,6 +236,15 @@ class ReverseProxiedEnvironment(object):
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
return map(to_wsgi_format, values)
@staticmethod
def valid_ip(address):
import netaddr
try:
netaddr.IPAddress(address)
return True
except:
return False
def __init__(self,
header_prefix=None,
header_scheme=None,
@@ -290,11 +299,43 @@ class ReverseProxiedEnvironment(object):
if host is None:
return None, None
default_port = "443" if scheme == "https" else "80"
host = host.strip()
if ":" in host:
server, port = host.split(":", 1)
# we might have an ipv6 address here, or a port, or both
if host[0] == "[":
# that looks like an ipv6 address with port, e.g. [fec1::1]:80
address_end = host.find("]")
if address_end == -1:
# no ], that looks like a seriously broken address
return None, None
# extract server ip, skip enclosing [ and ]
server = host[1:address_end]
tail = host[address_end + 1:]
# now check if there's also a port
if len(tail) and tail[0] == ":":
# port included as well
port = tail[1:]
else:
# no port, use default one
port = default_port
elif self.__class__.valid_ip(host):
# ipv6 address without port
server = host
port = default_port
else:
# ipv4 address with port
server, port = host.rsplit(":", 1)
else:
server = host
port = "443" if scheme == "https" else "80"
port = default_port
return server, port
@@ -352,7 +393,12 @@ class ReverseProxiedEnvironment(object):
# default port for scheme, can be skipped
environ["HTTP_HOST"] = environ["SERVER_NAME"]
else:
environ["HTTP_HOST"] = environ["SERVER_NAME"] + ":" + environ["SERVER_PORT"]
server_name_component = environ["SERVER_NAME"]
if ":" in server_name_component and self.__class__.valid_ip(server_name_component):
# this is an ipv6 address, we need to wrap that in [ and ] before appending the port
server_name_component = "[" + server_name_component + "]"
environ["HTTP_HOST"] = server_name_component + ":" + environ["SERVER_PORT"]
# call wrapped app with rewritten environment
return environ
@@ -1251,6 +1297,7 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
'js/app/bindings/slimscrolledforeach.js',
'js/app/bindings/toggle.js',
'js/app/bindings/togglecontent.js',
'js/app/bindings/valuewithinit.js',
'js/app/viewmodels/appearance.js',
'js/app/viewmodels/connection.js',
'js/app/viewmodels/control.js',
+7 -5
View File
@@ -77,7 +77,9 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
display_version=octoprint.server.DISPLAY_VERSION,
branch=octoprint.server.BRANCH,
plugin_hash=plugin_hash.hexdigest(),
config_hash=config_hash
config_hash=config_hash,
debug=octoprint.server.debug,
safe_mode=octoprint.server.safe_mode
))
self._printer.register_callback(self)
@@ -152,12 +154,12 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
messages = self._messageBacklog
self._messageBacklog = []
busy_files = [dict(origin=v[0], name=v[1]) for v in self._fileManager.get_busy_files()]
busy_files = [dict(origin=v[0], path=v[1]) for v in self._fileManager.get_busy_files()]
if "job" in data and data["job"] is not None \
and "file" in data["job"] and "name" in data["job"]["file"] and "origin" in data["job"]["file"] \
and data["job"]["file"]["name"] is not None and data["job"]["file"]["origin"] is not None \
and "file" in data["job"] and "path" in data["job"]["file"] and "origin" in data["job"]["file"] \
and data["job"]["file"]["path"] is not None and data["job"]["file"]["origin"] is not None \
and (self._printer.is_printing() or self._printer.is_paused()):
busy_files.append(dict(origin=data["job"]["file"]["origin"], name=data["job"]["file"]["name"]))
busy_files.append(dict(origin=data["job"]["file"]["origin"], path=data["job"]["file"]["path"]))
data.update({
"serverTime": time.time(),
+8 -6
View File
@@ -27,7 +27,7 @@ from . import util
import logging
_logger = logging.getLogger(__name__)
_templates = None
_templates = dict()
_plugin_names = None
_plugin_vars = None
@@ -159,19 +159,21 @@ def index():
preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"])
locale = g.locale.language if g.locale else "en"
# helper to check if wizards are active
def wizard_active(templates):
return templates is not None and bool(templates["wizard"]["order"])
# we force a refresh if the client forces one or if we have wizards cached
force_refresh = util.flask.cache_check_headers() or "_refresh" in request.values or wizard_active(_templates)
force_refresh = util.flask.cache_check_headers() or "_refresh" in request.values or wizard_active(_templates.get(locale))
# if we need to refresh our template cache or it's not yet set, process it
if force_refresh or _templates is None or _plugin_names is None or _plugin_vars is None:
_templates, _plugin_names, _plugin_vars = _process_templates()
if force_refresh or _templates.get(locale) is None or _plugin_names is None or _plugin_vars is None:
_templates[locale], _plugin_names, _plugin_vars = _process_templates()
now = datetime.datetime.utcnow()
render_kwargs = _get_render_kwargs(_templates, _plugin_names, _plugin_vars, now)
render_kwargs = _get_render_kwargs(_templates[locale], _plugin_names, _plugin_vars, now)
def get_preemptively_cached_view(key, view, data=None, additional_request_data=None, additional_unless=None):
if (data is None and additional_request_data is None) or g.locale is None:
@@ -304,7 +306,7 @@ def index():
return view(now, request, render_kwargs)
def default_view():
wizard = wizard_active(_templates)
wizard = wizard_active(_templates[locale])
enable_accesscontrol = userManager.enabled
accesscontrol_active = enable_accesscontrol and userManager.hasBeenCustomized()
render_kwargs.update(dict(
+107 -37
View File
@@ -103,7 +103,7 @@ default_settings = {
"maxWritePasses": 5,
"additionalPorts": [],
"additionalBaudrates": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226"],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226", "M600"],
"checksumRequiringCommands": ["M110"],
"helloCommand": "M110 N0",
"disconnectOnErrors": True,
@@ -118,6 +118,7 @@ default_settings = {
"host": "0.0.0.0",
"port": 5000,
"firstRun": True,
"startOnceInSafeMode": False,
"seenWizards": {},
"secretKey": None,
"reverseProxy": {
@@ -166,7 +167,8 @@ default_settings = {
"type": "off",
"options": {},
"postRoll": 0,
"fps": 25
"fps": 25,
"capturePostRoll": True
},
"cleanTmpAfterDays": 7
},
@@ -176,7 +178,9 @@ default_settings = {
"sizeThreshold": 20 * 1024 * 1024, # 20MB
},
"gcodeAnalysis": {
"maxExtruders": 10
"maxExtruders": 10,
"throttle_normalprio": 0.01,
"throttle_highprio": 0.0
},
"feature": {
"temperatureGraph": True,
@@ -197,7 +201,9 @@ default_settings = {
"ignoreIdenticalResends": False,
"identicalResendsCountdown": 7,
"supportFAsCommand": False,
"modelSizeDetection": True
"modelSizeDetection": True,
"firmwareDetection": True,
"printCancelConfirmation": True
},
"folder": {
"uploads": None,
@@ -289,8 +295,9 @@ default_settings = {
"apps": {}
},
"terminalFilters": [
{ "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok (B|T\d*):)" },
{ "name": "Suppress M27 requests/responses", "regex": "(Send: M27)|(Recv: SD printing byte)" }
{ "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv: ok (B|T\d*):)" },
{ "name": "Suppress SD status messages", "regex": "(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)" },
{ "name": "Suppress wait responses", "regex": "Recv: wait"}
],
"plugins": {
"_disabled": []
@@ -332,12 +339,6 @@ default_settings = {
"numExtruders": 1,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
"movementSpeed": {
"x": 6000,
"y": 6000,
"z": 200,
"e": 300
},
"hasBed": True,
"repetierStyleTargetTemperature": False,
"repetierStyleResends": False,
@@ -354,7 +355,8 @@ default_settings = {
"supportM112": True,
"echoOnM117": True,
"brokenM29": True,
"supportF": False
"supportF": False,
"firmwareName": "Virtual Marlin 1.0"
}
}
}
@@ -835,12 +837,17 @@ class Settings(object):
self._migrate_config(config)
return config
def add_overlay(self, overlay):
self._map.maps.insert(1, overlay)
def add_overlay(self, overlay, at_end=False):
if at_end:
pos = len(self._map.maps) - 1
self._map.maps.insert(pos, overlay)
else:
self._map.maps.insert(1, overlay)
def _migrate_config(self, config=None):
def _migrate_config(self, config=None, persist=False):
if config is None:
config = self._config
persist = True
dirty = False
@@ -848,12 +855,14 @@ class Settings(object):
self._migrate_event_config,
self._migrate_reverse_proxy_config,
self._migrate_printer_parameters,
self._migrate_gcode_scripts
self._migrate_gcode_scripts,
self._migrate_core_system_commands
)
for migrate in migrators:
dirty = migrate(config) or dirty
if dirty:
if dirty and persist:
self.save(force=True)
def _migrate_gcode_scripts(self, config):
@@ -1062,6 +1071,67 @@ class Settings(object):
else:
return False
def _migrate_core_system_commands(self, config):
"""
Migrates system commands for restart, reboot and shutdown as defined on OctoPi or
according to the official setup guide to new core system commands to remove
duplication.
If server commands for action is not yet set, migrates command. Otherwise only
deletes definition from custom system commands.
"""
changed = False
migration_map = dict(shutdown="systemShutdownCommand",
reboot="systemRestartCommand",
restart="serverRestartCommand")
if "system" in config and "actions" in config["system"]:
actions = config["system"]["actions"]
to_delete = []
for index, spec in enumerate(actions):
action = spec.get("action")
command = spec.get("command")
if action is None or command is None:
continue
migrate_to = migration_map.get(action)
if migrate_to is not None:
if not "server" in config or not "commands" in config["server"] or not migrate_to in config["server"]["commands"]:
if not "server" in config:
config["server"] = dict()
if not "commands" in config["server"]:
config["server"]["commands"] = dict()
config["server"]["commands"][migrate_to] = command
self._logger.info("Migrated {} action to server.commands.{}".format(action, migrate_to))
to_delete.append(index)
self._logger.info("Deleting {} action from configured system commands, superseeded by server.commands.{}".format(action, migrate_to))
for index in reversed(to_delete):
actions.pop(index)
changed = True
if changed:
# let's make a backup of our current config, in case someone wants to roll back to an
# earlier version and needs to recover the former system commands for that
backup_path = self.backup("system_command_migration")
self._logger.info("Made a copy of the current config at {} to allow recovery of manual system command configuration".format(backup_path))
return changed
def backup(self, suffix, path=None):
import shutil
if path is None:
path = os.path.dirname(self._configfile)
basename = os.path.basename(self._configfile)
name, ext = os.path.splitext(basename)
backup = os.path.join(path, "{}.{}{}".format(name, suffix, ext))
shutil.copy(self._configfile, backup)
return backup
def save(self, force=False):
if not self._dirty and not force:
return False
@@ -1105,12 +1175,14 @@ class Settings(object):
else:
chain = self._map
if preprocessors is None:
preprocessors = self._get_preprocessors
preprocessor = None
if preprocessors is not None:
try:
preprocessor = self._get_by_path(path, preprocessors)
except NoSuchSettingsPath:
pass
try:
preprocessor = self._get_by_path(path, preprocessors)
except NoSuchSettingsPath:
pass
parent_path = path[:-1]
last = path[-1]
@@ -1310,15 +1382,17 @@ class Settings(object):
else:
chain = self._map
preprocessor = None
if preprocessors is not None:
try:
preprocessor = self._get_by_path(path, preprocessors)
except NoSuchSettingsPath:
pass
if preprocessors is None:
preprocessors = self._set_preprocessors
if callable(preprocessor):
value = preprocessor(value)
preprocessor = None
try:
preprocessor = self._get_by_path(path, preprocessors)
except NoSuchSettingsPath:
pass
if callable(preprocessor):
value = preprocessor(value)
try:
current = chain.get_by_path(path)
@@ -1416,12 +1490,8 @@ class Settings(object):
def _default_basedir(applicationName):
# taken from http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python
if sys.platform == "darwin":
from AppKit import NSSearchPathForDirectoriesInDomains
# http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains
# NSApplicationSupportDirectory = 14
# NSUserDomainMask = 1
# True for expanding the tilde into a fully qualified path
return os.path.join(NSSearchPathForDirectoriesInDomains(14, 1, True)[0], applicationName)
import appdirs
return appdirs.user_data_dir(applicationName, "")
elif sys.platform == "win32":
return os.path.join(os.environ["APPDATA"], applicationName)
else:
+1 -1
View File
@@ -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
+67
View File
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="16"
height="16"
id="svg4693"
version="1.1"
inkscape:version="0.48.4 r9939"
sodipodi:docname="octoprint-favicon-apple.svg">
<defs
id="defs4695" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="31.678384"
inkscape:cx="11.852657"
inkscape:cy="8.0632297"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="1912"
inkscape:window-y="760"
inkscape:window-maximized="1" />
<metadata
id="metadata4698">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-1036.3622)">
<path
inkscape:connector-curvature="0"
style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:0.30326968;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
d="m 8.4712216,1037.1861 c -2.1050908,0.04 -4.0163689,0.8056 -5.7487668,2.3398 -1.0712052,0.9142 -1.82198358,1.9725 -2.25345195,3.1787 -0.37398533,1.751 -0.40029296,3.4654 -0.0863535,5.0991 0.18720389,1.0348 0.58340878,2.2568 1.19251915,3.6886 l 4.2190532,0 c -0.293453,-0.8621 -0.577953,-1.5323 -0.8471012,-2.0232 -1.153287,-2.1277 -1.411065,-4.2066 -0.7607457,-6.2052 0.2367104,-0.6185 0.5586836,-1.2169 0.9581276,-1.7806 0.1426595,-0.2013 0.3287285,-0.4113 0.5345786,-0.588 0.268515,-0.2936 0.8787071,-0.6679 1.8463495,-1.1514 0.3797863,-0.1946 0.7802208,-0.3318 1.2254154,-0.4195 0.055375,-0.021 0.4121338,-0.071 1.0485963,-0.1439 0.4166658,-0.047 0.9826928,0.01 1.7024248,0.218 0.68338,0.202 1.192041,0.4217 1.554388,0.6785 0.46971,0.3328 0.860598,0.6899 1.196632,1.0691 0.08834,0.1029 0.152532,0.1851 0.217943,0.292 0.119092,0.1449 0.28643,0.3643 0.501681,0.6579 0.120782,0.086 0.202303,0.1674 0.217943,0.2591 0.04417,0.051 0.07097,0.072 0.115138,0.1233 0.109582,0.1583 0.220475,0.3159 0.316636,0.4647 0.07883,0.1164 0.137371,0.2581 0.193271,0.3783 0.07894,-0.3674 0.06507,-0.8608 -0.08636,-1.4721 -0.180483,-0.7126 -0.391176,-1.2047 -0.633269,-1.5174 -0.507116,-0.6215 -0.808763,-0.9976 -0.933455,-1.1062 -0.03075,-0.042 -0.311374,-0.2417 -0.834763,-0.6127 -0.48313,-0.3423 -0.991284,-0.6213 -1.496819,-0.8183 -0.992045,-0.4208 -2.1359359,-0.6284 -3.3596164,-0.6086 z"
id="path3017-7-8"
sodipodi:nodetypes="ccccccccscccccsccccccccccscc" />
<path
inkscape:connector-curvature="0"
style="fill:#000000;stroke:#000000;stroke-width:0.30326967999999999;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;fill-opacity:1"
d="m 10.140749,1039.1641 c -0.122741,0 -0.2371399,0 -0.3413068,0.016 -0.6364625,0.073 -0.9932215,0.1227 -1.0485963,0.1439 -0.4451946,0.088 -0.8456291,0.2249 -1.2254154,0.4195 -0.9676424,0.4835 -1.5778345,0.8578 -1.8463495,1.1514 -0.2058501,0.1767 -0.3919191,0.3867 -0.5345786,0.588 -0.399444,0.5637 -0.7214172,1.1621 -0.9581276,1.7806 -0.6503193,1.9986 -0.3925413,4.0775 0.7607457,6.2052 0.2691482,0.4909 0.5536482,1.1611 0.8471012,2.0232 l 4.2601723,0 c -0.1550496,-0.4598 -0.3855015,-0.9829 -0.7113982,-1.5709 -0.2465293,-0.4771 -0.5321843,-0.9815 -0.8553245,-1.4927 -0.013422,-0.01 -0.00409,-0.021 -0.00409,-0.021 -0.051988,-0.097 -0.098669,-0.1734 -0.1562603,-0.2343 -0.030751,-0.042 -0.051492,-0.073 -0.082242,-0.1152 l -0.1809343,-0.2549 c -0.069319,-0.1298 -0.140197,-0.2592 -0.2056073,-0.366 -0.2460015,-0.3356 -0.4342851,-0.6086 -0.5880347,-0.8183 -0.1308197,-0.2137 -0.2609169,-0.4291 -0.3783173,-0.6333 -1.1170471,-1.6383 -1.0194278,-3.0575 0.2878496,-4.2478 0.3736582,-0.2997 0.8097656,-0.577 1.3405561,-0.7855 0.3188143,-0.1369 0.6574538,-0.2389 0.9745783,-0.3166 2.3182336,-0.3127 4.3630076,0.4721 6.1270826,2.3069 -0.09616,-0.1488 -0.207055,-0.3105 -0.316635,-0.4688 -0.04417,-0.051 -0.07097,-0.068 -0.115139,-0.1192 -0.01564,-0.092 -0.09716,-0.1735 -0.217944,-0.2591 -0.215251,-0.2936 -0.382589,-0.5131 -0.50168,-0.6579 -0.06541,-0.1069 -0.129604,-0.1891 -0.217944,-0.292 -0.336034,-0.3792 -0.726922,-0.7363 -1.196632,-1.0691 -0.362348,-0.2568 -0.871009,-0.4765 -1.554388,-0.6785 -0.539798,-0.1558 -0.992892,-0.2286 -1.361116,-0.2344 z"
id="path3101-4-0" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 5.0 KiB

@@ -0,0 +1,11 @@
ko.bindingHandlers.valueWithInit = {
init: function(element, valueAccessor, allBindingsAccessor, context) {
var observable = valueAccessor();
var value = element.value;
observable(value);
ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor, context);
},
update: ko.bindingHandlers.value.update
};
+13 -2
View File
@@ -46,7 +46,8 @@
OctoPrint.options = {
"baseurl": undefined,
"apikey": undefined
"apikey": undefined,
"locale": undefined
};
OctoPrint.plugins = {};
@@ -65,6 +66,10 @@
var headers = $.extend({}, additional);
headers["X-Api-Key"] = OctoPrint.options.apikey;
if (OctoPrint.options.locale !== undefined) {
headers["X-Locale"] = OctoPrint.options.locale;
}
return headers;
};
@@ -163,6 +168,7 @@
}
filename = filename || fileData.name;
var filesize = fileData.size;
var form = new FormData();
form.append("file", fileData, filename);
@@ -216,7 +222,12 @@
var headers = OctoPrint.getRequestHeaders();
request.open("POST", OctoPrint.getBaseUrl() + url);
var urlToCall = url;
if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) {
urlToCall = OctoPrint.getBaseUrl() + url;
}
request.open("POST", urlToCall);
_.each(headers, function(value, key) {
request.setRequestHeader(key, value);
});
+15 -4
View File
@@ -13,6 +13,8 @@ function DataUpdater(allViewModels) {
self._lastProcessingTimes = [];
self._lastProcessingTimesSize = 20;
self._safeModePopup = undefined;
self.increaseThrottle = function() {
self.setThrottle(self._throttleFactor + 1);
};
@@ -115,16 +117,25 @@ function DataUpdater(allViewModels) {
var oldConfigHash = self._configHash;
self._configHash = data["config_hash"];
// 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 are disabled and cannot be enabled.");
self._safeModePopup = new PNotify({
title: gettext("Safe mode is active"),
text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
hide: false
});
}
// if the offline overlay is still showing, now's a good time to
// hide it, plus reload the camera feed if it's currently displayed
if ($("#offline_overlay").is(":visible")) {
hideOfflineOverlay();
callViewModels(self.allViewModels, "onServerReconnect");
callViewModels(self.allViewModels, "onDataUpdaterReconnect");
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
}
} else {
callViewModels(self.allViewModels, "onServerConnect");
}
+33 -11
View File
@@ -777,9 +777,14 @@ function getOnlyChangedData(data, oldData) {
var retval = {};
_.forOwn(root, function(value, key) {
var oldValue = oldRoot[key];
var oldValue = undefined;
if (oldRoot != undefined && oldRoot.hasOwnProperty(key)) {
oldValue = oldRoot[key];
}
if (_.isPlainObject(value)) {
if (hasDataChanged(value, oldValue)) {
if (oldValue == undefined) {
retval[key] = value;
} else if (hasDataChanged(value, oldValue)) {
retval[key] = f(value, oldValue);
}
} else {
@@ -832,17 +837,21 @@ function callViewModelsIf(allViewModels, method, condition, callback) {
_.each(allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty(method) && condition(viewModel, method)) {
if (callback == undefined) {
if (parameters != undefined) {
// call the method with the provided parameters
viewModel[method].apply(viewModel, parameters);
try {
if (callback == undefined) {
if (parameters != undefined) {
// call the method with the provided parameters
viewModel[method].apply(viewModel, parameters);
} else {
// call the method without parameters
viewModel[method]();
}
} else {
// call the method without parameters
viewModel[method]();
// provide the method to the callback
callback(viewModel[method], viewModel);
}
} else {
// provide the method to the callback
callback(viewModel[method], viewModel);
} catch (exc) {
log.error("Error calling", method, "on view model", viewModel.constructor.name, ":", (exc.stack || exc));
}
}
});
@@ -861,3 +870,16 @@ var sizeObservable = function(observable) {
}
})
};
var getQueryParameterByName = function(name, url) {
// from http://stackoverflow.com/a/901144/2028598
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
+8 -1
View File
@@ -13,6 +13,11 @@ $(function() {
OctoPrint.options.baseurl = BASEURL;
OctoPrint.options.apikey = UI_API_KEY;
var l10n = getQueryParameterByName("l10n");
if (l10n) {
OctoPrint.options.locale = l10n;
}
OctoPrint.socket.onMessage("connected", function(data) {
var payload = data.data;
OctoPrint.options.apikey = payload.apikey;
@@ -31,7 +36,9 @@ $(function() {
OctoPrint.coreui = (function() {
var exports = {
browserTabVisibility: undefined,
selectedTab: undefined
selectedTab: undefined,
settingsOpen: false,
wizardOpen: false
};
var browserVisibilityCallbacks = [];
@@ -41,7 +41,7 @@ $(function() {
self.keycontrolActive = ko.observable(false);
self.keycontrolHelpActive = ko.observable(false);
self.keycontrolPossible = ko.pureComputed(function () {
return self.isOperational() && !self.isPrinting() && self.loginState.isUser() && !$.browser.mobile;
return self.settings.feature_keyboardControl() && self.isOperational() && !self.isPrinting() && self.loginState.isUser() && !$.browser.mobile;
});
self.showKeycontrols = ko.pureComputed(function () {
return self.keycontrolActive() && self.keycontrolPossible();
@@ -91,6 +91,8 @@ $(function() {
};
self.onEventSettingsUpdated = function (payload) {
// the webcam url might have changed, make sure we replace it now if the tab is focused
self._enableWebcam();
self.requestData();
};
@@ -378,9 +380,9 @@ $(function() {
}
var webcamImage = $("#webcam_image");
var currentSrc = webcamImage.attr("src");
if (currentSrc === undefined || currentSrc.trim() == "") {
var newSrc = CONFIG_WEBCAM_STREAM;
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
var newSrc = self.settings.webcam_streamUrl();
if (currentSrc != newSrc) {
if (newSrc.lastIndexOf("?") > -1) {
newSrc += "&";
} else {
newSrc += "?";
+34 -41
View File
@@ -402,13 +402,10 @@ $(function() {
if (!file) {
return;
}
OctoPrint.files.select(file.origin, file.path)
.done(function() {
var withinPrintDimensions = self.evaluatePrintDimensions(file, true);
if (withinPrintDimensions && printAfterLoad) {
OctoPrint.job.start();
}
});
var withinPrintDimensions = self.evaluatePrintDimensions(file, true);
var print = printAfterLoad && withinPrintDimensions;
OctoPrint.files.select(file.origin, file.path, print);
};
self.removeFile = function(file, event) {
@@ -444,20 +441,6 @@ $(function() {
};
self._removeEntry = function(entry, event) {
var index = self.listHelper.paginatedItems().indexOf(entry) + 1;
if (index >= self.listHelper.paginatedItems().length) {
index = index - 2;
}
if (index < 0) {
index = 0;
}
var focus = undefined;
var fileToFocus = self.listHelper.paginatedItems()[index];
if (fileToFocus) {
focus = {location: fileToFocus.origin, path: fileToFocus.path};
}
self.activeRemovals.push(entry.origin + ":" + entry.path);
var finishActiveRemoval = function() {
self.activeRemovals(_.filter(self.activeRemovals(), function(e) {
@@ -488,10 +471,7 @@ $(function() {
var deferred = $.Deferred();
OctoPrint.files.delete(entry.origin, entry.path)
.done(function() {
self.requestData({
focus: focus,
switchToPath: (entry.parent ? entry.parent.path : "")
})
self.requestData()
.done(function() {
deferred.resolve();
})
@@ -647,19 +627,31 @@ $(function() {
}
// set print volume boundaries
var boundaries = {
minX : 0,
maxX : volumeInfo.width(),
minY : 0,
maxY : volumeInfo.depth(),
minZ : 0,
maxZ : volumeInfo.height()
};
if (volumeInfo.origin() == "center") {
boundaries["maxX"] = volumeInfo.width() / 2;
boundaries["minX"] = -1 * boundaries["maxX"];
boundaries["maxY"] = volumeInfo.depth() / 2;
boundaries["minY"] = -1 * boundaries["maxY"];
var boundaries;
if (_.isPlainObject(volumeInfo.custom_box)) {
boundaries = {
minX : volumeInfo.custom_box.x_min(),
minY : volumeInfo.custom_box.y_min(),
minZ : volumeInfo.custom_box.z_min(),
maxX : volumeInfo.custom_box.x_max(),
maxY : volumeInfo.custom_box.y_max(),
maxZ : volumeInfo.custom_box.z_max()
}
} else {
boundaries = {
minX : 0,
maxX : volumeInfo.width(),
minY : 0,
maxY : volumeInfo.depth(),
minZ : 0,
maxZ : volumeInfo.height()
};
if (volumeInfo.origin() == "center") {
boundaries["maxX"] = volumeInfo.width() / 2;
boundaries["minX"] = -1 * boundaries["maxX"];
boundaries["maxY"] = volumeInfo.depth() / 2;
boundaries["minY"] = -1 * boundaries["maxY"];
}
}
// model not within bounds, we need to prepare a warning
@@ -716,11 +708,12 @@ $(function() {
return false;
}
if (entry["type"] == "folder" && entry["children"]) {
var success = entry["name"].toLocaleLowerCase().indexOf(query) > -1;
if (!success && entry["type"] == "folder" && entry["children"]) {
return _.any(entry["children"], recursiveSearch);
} else {
return entry["name"].toLocaleLowerCase().indexOf(query) > -1;
}
return success;
};
self.listHelper.changeSearchFunction(recursiveSearch);
@@ -76,6 +76,10 @@ $(function() {
self.loginUser("");
self.loginPass("");
self.loginRemember(false);
if (history && history.replaceState) {
history.replaceState({success: true}, document.title, window.location.pathname);
}
})
.fail(function() {
new PNotify({title: gettext("Login failed"), text: gettext("User unknown or wrong password"), type: "error"});
@@ -95,16 +99,11 @@ $(function() {
});
};
self.onLoginUserKeyup = function(data, event) {
if (event.keyCode == 13) {
self.elementPasswordInput.focus();
}
};
self.onLoginPassKeyup = function(data, event) {
if (event.keyCode == 13) {
self.login();
self.prepareLogin = function(data, event) {
if(event && event.preventDefault) {
event.preventDefault();
}
self.login();
};
self.onAllBound = function(allViewModels) {
@@ -120,6 +119,28 @@ $(function() {
self.elementUsernameInput = $("#login_user");
self.elementPasswordInput = $("#login_pass");
self.elementLoginButton = $("#login_button");
var toggle = $("li.dropdown#navbar_login");
var button = $("a", toggle);
button.on("click", function(e) {
$(this).parent().toggleClass("open");
});
$("body").on("click", function(e) {
var anyFormLinkOrButton = $("#login_dropdown_loggedout a, #login_dropdown_loggedin a, #login_dropdown_loggedout button, #login_dropdown_loggedin button");
var dropdown = $("li.dropdown#navbar_login");
var anyLastpassButton = $("#__lpform_login_user, #__lpform_login_pass");
var isLinkOrButton = anyFormLinkOrButton.is(e.target) || anyFormLinkOrButton.has(e.target).length !== 0;
var isDropdown = dropdown.is(e.target) || dropdown.has(e.target).length === 0;
var isLastpass = anyLastpassButton.is(e.target) || anyLastpassButton.has(e.target).length === 0;
if (isLinkOrButton || !(isDropdown || isLastpass)) {
toggle.removeClass("open");
}
});
if (self.elementUsernameInput && self.elementUsernameInput.length
&& self.elementLoginButton && self.elementLoginButton.length) {
self.elementLoginButton.blur(function() {
@@ -10,7 +10,8 @@ $(function() {
width: 200,
depth: 200,
height: 200,
origin: "lowerleft"
origin: "lowerleft",
custom_box: false
},
heatedBed: true,
axes: {
@@ -53,6 +54,9 @@ $(function() {
self.volumeOrigin("center");
}
});
self.volumeOrigin.subscribe(function() {
self.toBoundingBoxPlaceholders(self.defaultBoundingBox(self.volumeWidth(), self.volumeDepth(), self.volumeHeight(), self.volumeOrigin()));
});
self.heatedBed = ko.observable();
@@ -70,6 +74,20 @@ $(function() {
self.axisZInverted = ko.observable(false);
self.axisEInverted = ko.observable(false);
self.customBoundingBox = ko.observable(false);
self.boundingBoxMinX = ko.observable();
self.boundingBoxMinY = ko.observable();
self.boundingBoxMinZ = ko.observable();
self.boundingBoxMaxX = ko.observable();
self.boundingBoxMaxY = ko.observable();
self.boundingBoxMaxZ = ko.observable();
self.boundingBoxMinXPlaceholder = ko.observable();
self.boundingBoxMinYPlaceholder = ko.observable();
self.boundingBoxMinZPlaceholder = ko.observable();
self.boundingBoxMaxXPlaceholder = ko.observable();
self.boundingBoxMaxYPlaceholder = ko.observable();
self.boundingBoxMaxZPlaceholder = ko.observable();
self.koExtruderOffsets = ko.pureComputed(function() {
var extruderOffsets = self.extruderOffsets();
var numExtruders = self.extruders();
@@ -181,6 +199,13 @@ $(function() {
self.volumeFormFactor(data.volume.formFactor);
self.volumeOrigin(data.volume.origin);
if (data.volume.custom_box) {
self.toBoundingBoxData(data.volume.custom_box, true);
} else {
var box = self.defaultBoundingBox(data.volume.width, data.volume.depth, data.volume.height, data.volume.origin);
self.toBoundingBoxData(box, false);
}
self.heatedBed(data.heatedBed);
self.nozzleDiameter(data.extruder.nozzleDiameter);
@@ -268,6 +293,8 @@ $(function() {
}
};
self.fillBoundingBoxData(profile);
var offsetX, offsetY;
if (self.extruders() > 1) {
for (var i = 0; i < self.extruders() - 1; i++) {
@@ -288,6 +315,76 @@ $(function() {
return profile;
};
self.defaultBoundingBox = function(width, depth, height, origin) {
if (origin == "center") {
var halfWidth = width / 2.0;
var halfDepth = depth / 2.0;
return {
x_min: -halfWidth,
y_min: -halfDepth,
z_min: 0.0,
x_max: halfWidth,
y_max: halfDepth,
z_max: height
}
} else {
return {
x_min: 0.0,
y_min: 0.0,
z_min: 0.0,
x_max: width,
y_max: depth,
z_max: height
}
}
};
self.toBoundingBoxData = function(box, custom) {
self.customBoundingBox(custom);
if (custom) {
self.boundingBoxMinX(box.x_min);
self.boundingBoxMinY(box.y_min);
self.boundingBoxMinZ(box.z_min);
self.boundingBoxMaxX(box.x_max);
self.boundingBoxMaxY(box.y_max);
self.boundingBoxMaxZ(box.z_max);
} else {
self.boundingBoxMinX(undefined);
self.boundingBoxMinY(undefined);
self.boundingBoxMinZ(undefined);
self.boundingBoxMaxX(undefined);
self.boundingBoxMaxY(undefined);
self.boundingBoxMaxZ(undefined);
}
self.toBoundingBoxPlaceholders(box);
};
self.toBoundingBoxPlaceholders = function(box) {
self.boundingBoxMinXPlaceholder(box.x_min);
self.boundingBoxMinYPlaceholder(box.y_min);
self.boundingBoxMinZPlaceholder(box.z_min);
self.boundingBoxMaxXPlaceholder(box.x_max);
self.boundingBoxMaxYPlaceholder(box.y_max);
self.boundingBoxMaxZPlaceholder(box.z_max);
};
self.fillBoundingBoxData = function(profile) {
if (self.customBoundingBox()) {
var defaultBox = self.defaultBoundingBox(self.volumeWidth(), self.volumeDepth(), self.volumeHeight(), self.volumeOrigin());
profile.volume.custom_box = {
x_min: (self.boundingBoxMinX() !== undefined) ? Math.min(self.boundingBoxMinX(), defaultBox.x_min) : defaultBox.x_min,
y_min: (self.boundingBoxMinY() !== undefined) ? Math.min(self.boundingBoxMinY(), defaultBox.y_min) : defaultBox.y_min,
z_min: (self.boundingBoxMinZ() !== undefined) ? Math.min(self.boundingBoxMinZ(), defaultBox.z_min) : defaultBox.z_min,
x_max: (self.boundingBoxMaxX() !== undefined) ? Math.max(self.boundingBoxMaxX(), defaultBox.x_max) : defaultBox.x_max,
y_max: (self.boundingBoxMaxY() !== undefined) ? Math.max(self.boundingBoxMaxY(), defaultBox.y_max) : defaultBox.y_max,
z_max: (self.boundingBoxMaxZ() !== undefined) ? Math.max(self.boundingBoxMaxZ(), defaultBox.z_max) : defaultBox.z_max
};
} else {
profile.volume.custom_box = false;
}
};
self._sanitize = function(name) {
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
};
@@ -3,6 +3,7 @@ $(function() {
var self = this;
self.loginState = parameters[0];
self.settings = parameters[1];
self.stateString = ko.observable(undefined);
self.isErrorOrClosed = ko.observable(undefined);
@@ -255,8 +256,8 @@ $(function() {
self._processBusyFiles = function(data) {
var busyFiles = [];
_.each(data, function(entry) {
if (entry.hasOwnProperty("name") && entry.hasOwnProperty("origin")) {
busyFiles.push(entry.origin + ":" + entry.name);
if (entry.hasOwnProperty("path") && entry.hasOwnProperty("origin")) {
busyFiles.push(entry.origin + ":" + entry.path);
}
});
self.busyFiles(busyFiles);
@@ -288,13 +289,24 @@ $(function() {
};
self.cancel = function() {
OctoPrint.job.cancel();
if (!self.settings.feature_printCancelConfirmation()) {
OctoPrint.job.cancel();
} else {
showConfirmationDialog({
message: gettext("This will cancel your print."),
cancel: gettext("No"),
proceed: gettext("Yes"),
onproceed: function() {
OctoPrint.job.cancel();
}
});
}
};
}
OCTOPRINT_VIEWMODELS.push([
PrinterStateViewModel,
["loginStateViewModel"],
["loginStateViewModel", "settingsViewModel"],
["#state_wrapper", "#drop_overlay"]
]);
});
@@ -16,6 +16,10 @@ $(function() {
});
self.outstanding = [];
self.active = false;
self.sawUpdateEventWhileActive = false;
self.ignoreNextUpdateEvent = false;
self.settingsDialog = undefined;
self.settings_dialog_update_detected = undefined;
self.translationManagerDialog = undefined;
@@ -133,6 +137,8 @@ $(function() {
self.feature_pollWatched = ko.observable(undefined);
self.feature_ignoreIdenticalResends = ko.observable(undefined);
self.feature_modelSizeDetection = ko.observable(undefined);
self.feature_firmwareDetection = ko.observable(undefined);
self.feature_printCancelConfirmation = ko.observable(undefined);
self.serial_port = ko.observable();
self.serial_baudrate = ko.observable();
@@ -355,12 +361,14 @@ $(function() {
self.allViewModels = allViewModels;
self.settingsDialog.on('show', function(event) {
OctoPrint.coreui.settingsOpen = true;
if (event.target.id == "settings_dialog") {
self.requestTranslationData();
callViewModels(allViewModels, "onSettingsShown");
}
});
self.settingsDialog.on('hidden', function(event) {
OctoPrint.coreui.settingsOpen = false;
if (event.target.id == "settings_dialog") {
callViewModels(allViewModels, "onSettingsHidden");
}
@@ -727,6 +735,7 @@ $(function() {
self.settingsDialog.trigger("beforeSave");
self.sawUpdateEventWhileSending = false;
self.sending(data == undefined || options.sending || false);
if (data == undefined) {
@@ -734,10 +743,15 @@ $(function() {
data = getOnlyChangedData(self.getLocalData(), self.lastReceivedSettings);
}
self.active = true;
return OctoPrint.settings.save(data)
.done(function(data, status, xhr) {
self.ignoreNextUpdateEvent = !self.sawUpdateEventWhileSending;
self.active = false;
self.receiving(true);
self.sending(false);
try {
self.fromResponse(data);
if (options.success) options.success(data, status, xhr);
@@ -747,6 +761,7 @@ $(function() {
})
.fail(function(xhr, status, error) {
self.sending(false);
self.active = false;
if (options.error) options.error(xhr, status, error);
})
.always(function(xhr, status) {
@@ -755,6 +770,10 @@ $(function() {
};
self.onEventSettingsUpdated = function() {
if (self.active) {
self.sawUpdateEventWhileActive = true;
}
var preventSettingsRefresh = _.any(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onSettingsPreventRefresh")) {
try {
@@ -775,7 +794,8 @@ $(function() {
if (self.isDialogActive()) {
// dialog is open and not currently busy...
if (self.sending() || self.receiving()) {
if (self.sending() || self.receiving() || self.active || self.ignoreNextUpdateEvent) {
self.ignoreNextUpdateEvent = false;
return;
}
@@ -806,6 +826,12 @@ $(function() {
$('ul.nav-list a:first', self.settingsDialog).tab("show");
}
};
self.onServerReconnect = function() {
// the settings might have changed if the server was just restarted,
// better refresh them now
self.requestData();
};
}
OCTOPRINT_VIEWMODELS.push([
@@ -28,7 +28,9 @@ $(function() {
action.actionSource = "core";
actions.push(action);
});
actions.push({action: "divider"});
if (response.custom && response.custom.length) {
actions.push({action: "divider"});
}
}
_.each(response.custom, function(data) {
var action = _.extend({}, data);
@@ -36,6 +36,10 @@ $(function() {
self.heaterOptions = ko.observable({});
self._printerProfileInitialized = false;
self._currentTemperatureDataBacklog = [];
self._historyTemperatureDataBacklog = [];
self._printerProfileUpdated = function() {
var graphColors = ["red", "orange", "green", "brown", "purple"];
var heaterOptions = {};
@@ -81,6 +85,10 @@ $(function() {
// write back
self.heaterOptions(heaterOptions);
self.tools(tools);
if (!self._printerProfileInitialized) {
self._triggerBacklog();
}
self.updatePlot();
};
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
@@ -126,16 +134,36 @@ $(function() {
self.fromCurrentData = function(data) {
self._processStateData(data.state);
self._processTemperatureUpdateData(data.serverTime, data.temps);
if (!self._printerProfileInitialized) {
self._currentTemperatureDataBacklog.push(data);
} else {
self._processTemperatureUpdateData(data.serverTime, data.temps);
}
self._processOffsetData(data.offsets);
};
self.fromHistoryData = function(data) {
self._processStateData(data.state);
self._processTemperatureHistoryData(data.serverTime, data.temps);
if (!self._printerProfileInitialized) {
self._historyTemperatureDataBacklog.push(data);
} else {
self._processTemperatureHistoryData(data.serverTime, data.temps);
}
self._processOffsetData(data.offsets);
};
self._triggerBacklog = function() {
_.each(self._historyTemperatureDataBacklog, function(data) {
self._processTemperatureHistoryData(data.serverTime, data.temps);
});
_.each(self._currentTemperatureDataBacklog, function(data) {
self._processTemperatureUpdateData(data.serverTime, data.temps);
});
self._historyTemperatureDataBacklog = [];
self._currentTemperatureDataBacklog = [];
self._printerProfileInitialized = true;
};
self._processStateData = function(data) {
self.isErrorOrClosed(data.flags.closedOrError);
self.isOperational(data.flags.operational);
@@ -217,14 +245,17 @@ $(function() {
})
});
var filterOld = function(item) {
return item[0] >= clientTime - self.temperature_cutoff() * 60 * 1000;
};
var temperature_cutoff = self.temperature_cutoff();
if (temperature_cutoff != undefined) {
var filterOld = function(item) {
return item[0] >= clientTime - temperature_cutoff * 60 * 1000;
};
_.each(_.keys(self.heaterOptions()), function(d) {
result[d].actual = _.filter(result[d].actual, filterOld);
result[d].target = _.filter(result[d].target, filterOld);
});
_.each(_.keys(self.heaterOptions()), function(d) {
result[d].actual = _.filter(result[d].actual, filterOld);
result[d].target = _.filter(result[d].target, filterOld);
});
}
return result;
};
@@ -10,12 +10,14 @@ $(function() {
self.defaultPostRoll = 0;
self.defaultInterval = 10;
self.defaultRetractionZHop = 0;
self.defaultCapturePostroll = true;
self.timelapseType = ko.observable(undefined);
self.timelapseTimedInterval = ko.observable(self.defaultInterval);
self.timelapsePostRoll = ko.observable(self.defaultPostRoll);
self.timelapseFps = ko.observable(self.defaultFps);
self.timelapseRetractionZHop = ko.observable(self.defaultRetractionZHop);
self.timelapseCapturePostRoll = ko.observable(self.defaultCapturePostRoll);
self.persist = ko.observable(false);
self.isDirty = ko.observable(false);
@@ -61,6 +63,9 @@ $(function() {
self.timelapseRetractionZHop.subscribe(function(newValue) {
self.isDirty(true);
});
self.timelapseCapturePostRoll.subscribe(function() {
self.isDirty(true);
});
// initialize list helper
self.listHelper = new ItemListHelper(
@@ -167,6 +172,12 @@ $(function() {
self.timelapseFps(self.defaultFps);
}
if (config.capturePostRoll != undefined){
self.timelapseCapturePostRoll(config.capturePostRoll);
} else {
self.timelapseCapturePostRoll(self.defaultCapturePostRoll);
}
self.persist(false);
self.isDirty(false);
};
@@ -214,6 +225,7 @@ $(function() {
if (self.timelapseType() == "timed") {
payload["interval"] = self.timelapseTimedInterval();
payload["capturePostRoll"] = self.timelapseCapturePostRoll();
}
if (self.timelapseType() == "zchange") {
@@ -43,6 +43,13 @@ $(function() {
self.onStartup = function() {
self.wizardDialog = $("#wizard_dialog");
self.wizardDialog.on('show', function(event) {
OctoPrint.coreui.wizardOpen = true;
});
self.wizardDialog.on('hidden', function(event) {
OctoPrint.coreui.wizardOpen = false;
});
self.reloadOverlay = $("#reloadui_overlay");
};
+26
View File
@@ -1139,3 +1139,29 @@ input[type=number] {
width: 100%;
}
}
// Navbar loginForm
// Make the overlay always visible so that extensions are able to auto-submit (i.e. password-managers)
#navbar_login:not(.open) #login_dropdown_loggedout {
display: block;
z-index: -1;
height: 0;
width: 0;
padding: 0 !important;
overflow: hidden;
border: 0;
box-shadow: none;
left: -9999px;
&.hide {
display: none;
}
}
#loginForm {
margin: 0;
button {
margin-top: 20px;
}
}
@@ -1,77 +0,0 @@
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Form Factor') }}</label>
<div class="controls">
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="rectangular" data-bind="checked: volumeFormFactor"> {{ _('Rectangular') }}</label>
</div>
<div class="controls">
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="circular" data-bind="checked: volumeFormFactor"> {{ _('Circular') }}</label>
</div>
</div>
<div class="control-group">
<div class="control-group">
<label class="control-label">{{ _('Origin') }}</label>
<div class="controls">
<select data-bind="value: volumeOrigin, options: availableOrigins, optionsText: 'name', optionsValue: 'key'">
</select>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Heated Bed') }}</label>
<div class="controls">
<input type="checkbox" data-bind="checked: heatedBed">
</div>
</div>
<div class="control-group">
<div class="controls">
{{ _('Please define the print volume.') }}
</div>
</div>
<div data-bind="visible: volumeFormFactor() != 'circular'" style="display: none">
<div class="control-group">
<label class="control-label">{{ _('Width (X)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeWidth" placeholder="200">
<span class="add-on">mm</span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Depth (Y)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeDepth" placeholder="200">
<span class="add-on">mm</span>
</div>
</div>
</div>
</div>
<div data-bind="visible: volumeFormFactor() == 'circular'" style="display: none">
<div class="control-group">
<label class="control-label">{{ _('Diameter (X/Y)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeWidth" placeholder="200">
<span class="add-on">mm</span>
</div>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Height (Z)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeHeight" placeholder="200">
<span class="add-on">mm</span>
</div>
</div>
</div>
<p>
<small>{{ _('This information is used for the GCODE Viewer and/or when slicing from OctoPrint. It does NOT influence already sliced files that you upload to OctoPrint!') }}</small>
</p>
</form>
+1 -1
View File
@@ -1,7 +1,7 @@
<div id="add_folder_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>Create Folder</h3>
<h3>{{ _('Create Folder') }}</h3>
</div>
<div class="modal-body">
<p>{{ _('Please specify the name of the folder to create.') }}</p>
@@ -13,6 +13,13 @@
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_printCancelConfirmation" id="settings-printCancelConfirmation"> {{ _('Confirm before cancelling a print') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
@@ -37,50 +44,63 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdRelativePath" id="settings-sdRelativePath"> {{ _('Select SD files by relative path') }} <span class="label">{{ _('RepRap Firmware') }}</span>
<input type="checkbox" data-bind="checked: feature_firmwareDetection" id="settings-firmwareDetection"> {{ _('Enable automatic firmware detection') }}
<span class="help-inline">{% trans %}
If enabled, OctoPrint will try to figure out your printer's firmware automatically and adjust a couple of communication parameters based on that.
If that doesn't work out, or you want more granular control, uncheck this and the parameters in question will become visible for you to adjust.
{% endtrans %}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdAlwaysAvailable" id="settings-featureSdAlwaysAvailable"> {{ _('Always assume SD card is present') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<div data-bind="visible: !feature_firmwareDetection()">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdRelativePath" id="settings-sdRelativePath"> {{ _('Select SD files by relative path') }} <span class="label">{{ _('RepRap Firmware') }}</span>
</label>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_ignoreIdenticalResends" id="settings-ignoreIdenticalResends"> {{ _('Ignore consecutive resend requests for the same line') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdAlwaysAvailable" id="settings-featureSdAlwaysAvailable"> {{ _('Always assume SD card is present') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_repetierTargetTemp" id="settings-featureRepetierTargetTemp"> {{ _('Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_ignoreIdenticalResends" id="settings-ignoreIdenticalResends"> {{ _('Ignore consecutive resend requests for the same line') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_disableExternalHeatupDetection" id="settings-featureExternalHeatupDetection"> {{ _('Disable detection of external heatups') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_repetierTargetTemp" id="settings-featureRepetierTargetTemp"> {{ _('Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Send a checksum with the command')}}</label>
<div class="controls">
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="print" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumPrint"> {{ _('When printing') }}
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="always" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumAlways"> {{ _('Always') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="never" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumNever"> {{ _('Never') }}
</label>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_disableExternalHeatupDetection" id="settings-featureExternalHeatupDetection"> {{ _('Disable detection of external heatups') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Send a checksum with the command')}}</label>
<div class="controls">
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="print" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumPrint"> {{ _('When printing') }}
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="always" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumAlways"> {{ _('Always') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="never" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumNever"> {{ _('Never') }}
</label>
</div>
</div>
</div>
</form>
@@ -1,7 +1,7 @@
<h3>{{ _('Printer Profiles') }}</h3>
{% include "_snippets/settings/printerprofiles/profiles.jinja2" %}
{% include "snippets/settings/printerprofiles/profiles.jinja2" %}
<button class="btn pull-right" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog(); }">{{ _('Add Profile...') }}</button>
{% include "_snippets/settings/printerprofiles/profileEditor.jinja2" %}
{% include "snippets/settings/printerprofiles/profileEditor.jinja2" %}
@@ -1,7 +1,7 @@
<form class="form-horizontal">
<h3>{{ _('Commands') }}</h3>
{% include "_snippets/settings/server/serverCommandServerRestart.jinja2" %}
{% include "_snippets/settings/server/serverCommandSystemRestart.jinja2" %}
{% include "_snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
{% include "snippets/settings/server/serverCommandServerRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %}
{% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %}
</form>
@@ -1,21 +1,21 @@
<h3>{{ _('Webcam') }}</h3>
<form class="form-horizontal">
{% include "_snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "_snippets/settings/webcam/webcamOrientation.jinja2" %}
{% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "snippets/settings/webcam/webcamOrientation.jinja2" %}
</form>
<h3>{{ _('Timelapse Recordings') }}</h3>
<form class="form-horizontal">
{% include "_snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
{% include "_snippets/settings/webcam/ffmpegPath.jinja2" %}
{% include "_snippets/settings/webcam/watermark.jinja2" %}
{% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
{% include "snippets/settings/webcam/ffmpegPath.jinja2" %}
{% include "snippets/settings/webcam/watermark.jinja2" %}
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'icon-caret-right icon-caret-down', parent: '.form-horizontal', container: '.hide' }"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
{% include "_snippets/settings/webcam/ffmpegBitrate.jinja2" %}
{% include "_snippets/settings/webcam/ffmpegThreads.jinja2" %}
{% include "snippets/settings/webcam/ffmpegBitrate.jinja2" %}
{% include "snippets/settings/webcam/ffmpegThreads.jinja2" %}
</div>
</div>
</form>
@@ -7,6 +7,6 @@
<p>{% trans url='http://octoprint.org/support-octoprint/' %}
If you enjoy OctoPrint, please consider <a href="{{ url }}" target="_blank">supporting its ongoing
development</a>. You can find find this link also in the "About" dialog. Thank you!
development</a>, which is fully funded by users like you! You can also find this link in the "About" dialog. <strong>Thank you!</strong>
{% endtrans %}</p>
+2
View File
@@ -4,6 +4,7 @@
<title data-bind="text: title">OctoPrint</title>
<link rel="shortcut icon" href="{{ url_for('static', filename='img/tentacle-32x32.png') }}">
<link rel="mask-icon" href="{{ url_for('static', filename='img/favicon.svg') }}" color="#56BE37">
<link rel="apple-touch-icon" sizes="114x114" href="{{ url_for('static', filename='img/apple-touch-icon-114x114.png') }}">
<link rel="apple-touch-icon" sizes="144x144" href="{{ url_for('static', filename='img/apple-touch-icon-144x144.png') }}">
@@ -119,6 +120,7 @@
<li><a href="https://github.com/foosel/OctoPrint/" target="_blank" rel="noreferrer noopener"><i class="icon-github"></i> {{ _('Sourcecode') }}</a></li>
<li><a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener"><i class="icon-book"></i> {{ _('Documentation') }}</a></li>
<li><a href="https://github.com/foosel/OctoPrint/issues" target="_blank" rel="noreferrer noopener"><i class="icon-flag"></i> {{ _('Bugs and Requests') }}</a></li>
<li><a href="https://github.com/foosel/OctoPrint/wiki/FAQ" target="_blank" rel="noreferrer noopener"><i class="icon-question-sign"></i> {{ _('FAQ') }}</a></li>
<li id="footer_about"><a href="javascript:void(0)" data-bind="click: show"><i class="icon-info-sign"></i> {{ _('About') }}</a></li>
</ul>
</div>
+1 -1
View File
@@ -10,7 +10,7 @@
var CONFIG_TIMELAPSEFILESPERPAGE = 10;
var CONFIG_LOGFILESPERPAGE = 10;
var CONFIG_USERSPERPAGE = 10;
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}";
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}"; // deprecated, only left for compatibility reasons
var CONFIG_ACCESS_CONTROL = {% if enableAccessControl -%} true; {% else %} false; {%- endif %}
var CONFIG_ACCESS_CONTROL_ACTIVE = {% if accessControlActive -%} true; {% else %} false; {%- endif %}
var CONFIG_SD_SUPPORT = {% if enableSdSupport -%} true; {% else %} false; {%- endif %}
+11 -9
View File
@@ -1,16 +1,18 @@
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<a href="#" class="dropdown-toggle">
<i class="icon-user"></i> <span data-bind="text: loginState.userMenuText">{{ _('Login') }}</span>
<b class="caret"></b>
</a>
<div id="login_dropdown_loggedout" style="padding: 15px" class="dropdown-menu" data-bind="css: {hide: loginState.loggedIn(), 'dropdown-menu': !loginState.loggedIn()}">
<label for="login_user">{{ _('Username') }}</label>
<input type="text" id="login_user" data-bind="value: loginState.loginUser, event: {'keyup': loginState.onLoginUserKeyup}" placeholder="{{ _('Username') }}" autocapitalize="none">
<label for="login_pass">{{ _('Password') }}</label>
<input type="password" id="login_pass" data-bind="value: loginState.loginPass, event: {'keyup': loginState.onLoginPassKeyup}" placeholder="{{ _('Password') }}">
<label class="checkbox">
<input type="checkbox" id="login_remember" data-bind="checked: loginState.loginRemember"> {{ _('Remember me') }}
</label>
<button class="btn btn-block btn-primary" id="login_button" data-bind="click: function() { loginState.login(); }">{{ _('Login') }}</button>
<form id="loginForm" data-bind="event: {'submit': loginState.prepareLogin }">
<label for="login_user">{{ _('Username') }}</label>
<input type="text" id="login_user" name="username" data-bind="valueWithInit: loginState.loginUser" placeholder="{{ _('Username') }}" autocapitalize="none">
<label for="login_pass">{{ _('Password') }}</label>
<input type="password" id="login_pass" name="password" data-bind="valueWithInit: loginState.loginPass" placeholder="{{ _('Password') }}">
<label class="checkbox">
<input type="checkbox" id="login_remember" data-bind="checked: loginState.loginRemember"> {{ _('Remember me') }}
</label>
<button type="submit" class="btn btn-block btn-primary" id="login_button">{{ _('Login') }}</button>
</form>
</div>
<ul id="login_dropdown_loggedin" class="hide" data-bind="css: {hide: !loginState.loggedIn(), 'dropdown-menu': loginState.loggedIn()}">
<li><a href="#" id="usersettings_button" data-bind="click: function() { usersettings.show(); }">{{ _('User Settings') }}</a></li>
@@ -13,21 +13,21 @@
</ul>
<!-- ko with: printerProfiles.editor -->
<div class="tab-content scrollable">
<div class="tab-content">
<div id="settings_printerProfiles_editDialog_general" class="tab-pane active">
{% include '_snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorGeneral.jinja2' %}
</div>
<div id="settings_printerProfiles_editDialog_buildvolume" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2' %}
</div>
<div id="settings_printerProfiles_editDialog_axes" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorAxes.jinja2' %}
</div>
<div id="settings_printerProfiles_editDialog_extruder" class="tab-pane">
{% include '_snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
{% include 'snippets/settings/printerprofiles/profileEditorExtruder.jinja2' %}
</div>
</div>
<!-- /ko -->
@@ -0,0 +1,132 @@
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Form Factor') }}</label>
<div class="controls">
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="rectangular" data-bind="checked: volumeFormFactor"> {{ _('Rectangular') }}</label>
</div>
<div class="controls">
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="circular" data-bind="checked: volumeFormFactor"> {{ _('Circular') }}</label>
</div>
</div>
<div class="control-group">
<div class="control-group">
<label class="control-label">{{ _('Origin') }}</label>
<div class="controls">
<select data-bind="value: volumeOrigin, options: availableOrigins, optionsText: 'name', optionsValue: 'key'">
</select>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Heated Bed') }}</label>
<div class="controls">
<input type="checkbox" data-bind="checked: heatedBed">
</div>
</div>
<div class="control-group">
<div class="controls">
{{ _('Please define the print volume.') }}
</div>
</div>
<div data-bind="visible: volumeFormFactor() != 'circular'" style="display: none">
<div class="control-group">
<label class="control-label">{{ _('Width (X)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeWidth" placeholder="200">
<span class="add-on">mm</span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Depth (Y)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeDepth" placeholder="200">
<span class="add-on">mm</span>
</div>
</div>
</div>
</div>
<div data-bind="visible: volumeFormFactor() == 'circular'" style="display: none">
<div class="control-group">
<label class="control-label">{{ _('Diameter (X/Y)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeWidth" placeholder="200">
<span class="add-on">mm</span>
</div>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Height (Z)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: volumeHeight" placeholder="200">
<span class="add-on">mm</span>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">{% trans %}
If your printer's print head may move slightly outside the print volume (e.g. for nozzle cleaning routines)
you can define a custom safe bounding box for its movements below.
{% endtrans %}</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Custom bounding box') }}</label>
<div class="controls">
<input type="checkbox" data-bind="checked: customBoundingBox">
</div>
</div>
<div data-bind="visible: customBoundingBox">
<div class="control-group">
<label class="control-label">{{ _('X Coordinates') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on">Min</span>
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMinX, attr: {placeholder: boundingBoxMinXPlaceholder, max: boundingBoxMinXPlaceholder}">
</div>
<div class="input-prepend">
<span class="add-on">Max</span>
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMaxX, attr: {placeholder: boundingBoxMaxXPlaceholder, min: boundingBoxMaxXPlaceholder}">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Y Coordinates') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on">Min</span>
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMinY, attr: {placeholder: boundingBoxMinYPlaceholder, max: boundingBoxMinYPlaceholder}">
</div>
<div class="input-prepend">
<span class="add-on">Max</span>
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMaxY, attr: {placeholder: boundingBoxMaxYPlaceholder, min: boundingBoxMaxYPlaceholder}">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Z Coordinates') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on">Min</span>
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMinZ, attr: {placeholder: boundingBoxMinZPlaceholder, max: boundingBoxMinZPlaceholder}">
</div>
<div class="input-prepend">
<span class="add-on">Max</span>
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: boundingBoxMaxZ, attr: {placeholder: boundingBoxMaxZPlaceholder, min: boundingBoxMaxZPlaceholder}">
</div>
</div>
</div>
</div>
<p>
<small>{{ _('This information is used for the temperature tab, the bounding box check, the GCODE Viewer and/or when slicing from OctoPrint. It does NOT influence already sliced files that you upload to OctoPrint!') }}</small>
</p>
</form>
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more