PlaceholderParser.pm 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package Slic3r::GCode::PlaceholderParser;
  2. use strict;
  3. use warnings;
  4. sub new {
  5. # TODO: move this code to C++ constructor, remove this method
  6. my ($class) = @_;
  7. my $self = $class->_new;
  8. $self->apply_env_variables;
  9. $self->update_timestamp;
  10. return $self;
  11. }
  12. sub apply_env_variables {
  13. my ($self) = @_;
  14. $self->_single_set($_, $ENV{$_}) for grep /^SLIC3R_/, keys %ENV;
  15. }
  16. sub update_timestamp {
  17. my ($self) = @_;
  18. my @lt = localtime; $lt[5] += 1900; $lt[4] += 1;
  19. $self->_single_set('timestamp', sprintf '%04d%02d%02d-%02d%02d%02d', @lt[5,4,3,2,1,0]);
  20. $self->_single_set('year', "$lt[5]");
  21. $self->_single_set('month', "$lt[4]");
  22. $self->_single_set('day', "$lt[3]");
  23. $self->_single_set('hour', "$lt[2]");
  24. $self->_single_set('minute', "$lt[1]");
  25. $self->_single_set('second', "$lt[0]");
  26. $self->_single_set('version', $Slic3r::VERSION);
  27. }
  28. sub apply_config {
  29. my ($self, $config) = @_;
  30. # options with single value
  31. my @opt_keys = grep !$Slic3r::Config::Options->{$_}{multiline}, @{$config->get_keys};
  32. $self->_single_set($_, $config->serialize($_)) for @opt_keys;
  33. # options with multiple values
  34. foreach my $opt_key (@opt_keys) {
  35. my $value = $config->$opt_key;
  36. next unless ref($value) eq 'ARRAY';
  37. # TODO: this is a workaroud for XS string param handling
  38. # https://rt.cpan.org/Public/Bug/Display.html?id=94110
  39. "$_" for @$value;
  40. $self->_multiple_set("${opt_key}_" . $_, $value->[$_]."") for 0..$#$value;
  41. $self->_multiple_set($opt_key, $value->[0]."");
  42. if ($Slic3r::Config::Options->{$opt_key}{type} eq 'point') {
  43. $self->_multiple_set("${opt_key}_X", $value->[0]."");
  44. $self->_multiple_set("${opt_key}_Y", $value->[1]."");
  45. }
  46. }
  47. }
  48. # TODO: or this could be an alias
  49. sub set {
  50. my ($self, $key, $val) = @_;
  51. $self->_single_set($key, $val);
  52. }
  53. sub process {
  54. my ($self, $string, $extra) = @_;
  55. # extra variables have priority over the stored ones
  56. if ($extra) {
  57. my $regex = join '|', keys %$extra;
  58. $string =~ s/\[($regex)\]/$extra->{$1}/eg;
  59. }
  60. {
  61. my $regex = join '|', @{$self->_single_keys};
  62. $string =~ s/\[($regex)\]/$self->_single_get("$1")/eg;
  63. }
  64. {
  65. my $regex = join '|', @{$self->_multiple_keys};
  66. $string =~ s/\[($regex)\]/$self->_multiple_get("$1")/egx;
  67. # unhandled indices are populated using the first value
  68. $string =~ s/\[($regex)_\d+\]/$self->_multiple_get("$1")/egx;
  69. }
  70. return $string;
  71. }
  72. 1;