This file is indexed.

/usr/share/perl5/Slic3r/GUI/Tab.pm is in slic3r 1.1.7+dfsg-2+b1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
package Slic3r::GUI::Tab;
use strict;
use warnings;
use utf8;

use File::Basename qw(basename);
use List::Util qw(first);
use Wx qw(:bookctrl :dialog :keycode :icon :id :misc :panel :sizer :treectrl :window);
use Wx::Event qw(EVT_BUTTON EVT_CHOICE EVT_KEY_DOWN EVT_TREE_SEL_CHANGED);
use base 'Wx::Panel';

sub new {
    my $class = shift;
    my ($parent, %params) = @_;
    my $self = $class->SUPER::new($parent, -1, wxDefaultPosition, wxDefaultSize, wxBK_LEFT | wxTAB_TRAVERSAL);
    $self->{options} = []; # array of option names handled by this tab
    $self->{$_} = $params{$_} for qw(on_value_change on_presets_changed);
    
    # horizontal sizer
    $self->{sizer} = Wx::BoxSizer->new(wxHORIZONTAL);
    $self->{sizer}->SetSizeHints($self);
    $self->SetSizer($self->{sizer});
    
    # left vertical sizer
    my $left_sizer = Wx::BoxSizer->new(wxVERTICAL);
    $self->{sizer}->Add($left_sizer, 0, wxEXPAND | wxLEFT | wxTOP | wxBOTTOM, 3);
    
    my $left_col_width = 150;
    
    # preset chooser
    {
        
        # choice menu
        $self->{presets_choice} = Wx::Choice->new($self, -1, wxDefaultPosition, [$left_col_width, -1], []);
        $self->{presets_choice}->SetFont($Slic3r::GUI::small_font);
        
        # buttons
        $self->{btn_save_preset} = Wx::BitmapButton->new($self, -1, Wx::Bitmap->new("$Slic3r::var/disk.png", wxBITMAP_TYPE_PNG));
        $self->{btn_delete_preset} = Wx::BitmapButton->new($self, -1, Wx::Bitmap->new("$Slic3r::var/delete.png", wxBITMAP_TYPE_PNG));
        $self->{btn_save_preset}->SetToolTipString("Save current " . lc($self->title));
        $self->{btn_delete_preset}->SetToolTipString("Delete this preset");
        $self->{btn_delete_preset}->Disable;
        
        ### These cause GTK warnings:
        ###my $box = Wx::StaticBox->new($self, -1, "Presets:", wxDefaultPosition, [$left_col_width, 50]);
        ###my $hsizer = Wx::StaticBoxSizer->new($box, wxHORIZONTAL);
        
        my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL);
        
        $left_sizer->Add($hsizer, 0, wxEXPAND | wxBOTTOM, 5);
        $hsizer->Add($self->{presets_choice}, 1, wxRIGHT | wxALIGN_CENTER_VERTICAL, 3);
        $hsizer->Add($self->{btn_save_preset}, 0, wxALIGN_CENTER_VERTICAL);
        $hsizer->Add($self->{btn_delete_preset}, 0, wxALIGN_CENTER_VERTICAL);
    }
    
    # tree
    $self->{treectrl} = Wx::TreeCtrl->new($self, -1, wxDefaultPosition, [$left_col_width, -1], wxTR_NO_BUTTONS | wxTR_HIDE_ROOT | wxTR_SINGLE | wxTR_NO_LINES | wxBORDER_SUNKEN | wxWANTS_CHARS);
    $left_sizer->Add($self->{treectrl}, 1, wxEXPAND);
    $self->{icons} = Wx::ImageList->new(16, 16, 1);
    $self->{treectrl}->AssignImageList($self->{icons});
    $self->{iconcount} = -1;
    $self->{treectrl}->AddRoot("root");
    $self->{pages} = [];
    $self->{treectrl}->SetIndent(0);
    EVT_TREE_SEL_CHANGED($parent, $self->{treectrl}, sub {
        my $page = first { $_->{title} eq $self->{treectrl}->GetItemText($self->{treectrl}->GetSelection) } @{$self->{pages}}
            or return;
        $_->Hide for @{$self->{pages}};
        $page->Show;
        $self->{sizer}->Layout;
        $self->Refresh;
    });
    EVT_KEY_DOWN($self->{treectrl}, sub {
        my ($treectrl, $event) = @_;
        if ($event->GetKeyCode == WXK_TAB) {
            $treectrl->Navigate($event->ShiftDown ? &Wx::wxNavigateBackward : &Wx::wxNavigateForward);
        } else {
            $event->Skip;
        }
    });
    
    EVT_CHOICE($parent, $self->{presets_choice}, sub {
        $self->on_select_preset;
        $self->on_presets_changed;
    });
    
    EVT_BUTTON($self, $self->{btn_save_preset}, sub { $self->save_preset });
    
    EVT_BUTTON($self, $self->{btn_delete_preset}, sub {
        my $i = $self->{presets_choice}->GetSelection;
        return if $i == 0;  # this shouldn't happen but let's trap it anyway
        my $res = Wx::MessageDialog->new($self, "Are you sure you want to delete the selected preset?", 'Delete Preset', wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION)->ShowModal;
        return unless $res == wxID_YES;
        if (-e $self->{presets}[$i]{file}) {
            unlink $self->{presets}[$i]{file};
        }
        splice @{$self->{presets}}, $i, 1;
        $self->set_dirty(0);
        $self->{presets_choice}->Delete($i);
        $self->{presets_choice}->SetSelection(0);
        $self->on_select_preset;
        $self->on_presets_changed;
    });
    
    $self->{config} = Slic3r::Config->new;
    $self->build;
    if ($self->hidden_options) {
        $self->{config}->apply(Slic3r::Config->new_from_defaults($self->hidden_options));
        push @{$self->{options}}, $self->hidden_options;
    }
    $self->load_presets;
    
    return $self;
}

sub current_preset {
    my $self = shift;
    return $self->{presets}[ $self->{presets_choice}->GetSelection ];
}

sub get_preset {
    my $self = shift;
    return $self->{presets}[ $_[0] ];
}

sub save_preset {
    my ($self, $name) = @_;
    
    # since buttons (and choices too) don't get focus on Mac, we set focus manually
    # to the treectrl so that the EVT_* events are fired for the input field having
    # focus currently. is there anything better than this?
    $self->{treectrl}->SetFocus;
    
    if (!defined $name) {
        my $preset = $self->current_preset;
        my $default_name = $preset->{default} ? 'Untitled' : basename($preset->{name});
        $default_name =~ s/\.ini$//i;
    
        my $dlg = Slic3r::GUI::SavePresetWindow->new($self,
            title   => lc($self->title),
            default => $default_name,
            values  => [ map { my $name = $_->{name}; $name =~ s/\.ini$//i; $name } @{$self->{presets}} ],
        );
        return unless $dlg->ShowModal == wxID_OK;
        $name = $dlg->get_name;
    }
    
    $self->config->save(sprintf "$Slic3r::GUI::datadir/%s/%s.ini", $self->name, $name);
    $self->set_dirty(0);
    $self->load_presets;
    $self->{presets_choice}->SetSelection(first { basename($self->{presets}[$_]{file}) eq $name . ".ini" } 1 .. $#{$self->{presets}});
    $self->on_select_preset;
    $self->on_presets_changed;
}

# propagate event to the parent
sub on_value_change {
    my $self = shift;
    $self->{on_value_change}->(@_) if $self->{on_value_change};
}

sub on_presets_changed {
    my $self = shift;
    $self->{on_presets_changed}->([$self->{presets_choice}->GetStrings], $self->{presets_choice}->GetSelection)
        if $self->{on_presets_changed};
}

sub on_preset_loaded {}
sub hidden_options {}
sub config { $_[0]->{config}->clone }

sub select_default_preset {
    my $self = shift;
    $self->{presets_choice}->SetSelection(0);
}

sub select_preset {
    my $self = shift;
    $self->{presets_choice}->SetSelection($_[0]);
    $self->on_select_preset;
}

sub on_select_preset {
    my $self = shift;
    
    if (defined $self->{dirty}) {
        my $name = $self->{dirty} == 0 ? 'Default preset' : "Preset \"$self->{presets}[$self->{dirty}]{name}\"";
        my $confirm = Wx::MessageDialog->new($self, "$name has unsaved changes. Discard changes and continue anyway?",
                                             'Unsaved Changes', wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION);
        if ($confirm->ShowModal == wxID_NO) {
            $self->{presets_choice}->SetSelection($self->{dirty});
            return;
        }
        $self->set_dirty(0);
    }
    
    my $preset = $self->current_preset;
    my $preset_config = $self->get_preset_config($preset);
    eval {
        local $SIG{__WARN__} = Slic3r::GUI::warning_catcher($self);
        foreach my $opt_key (@{$self->{options}}) {
            $self->{config}->set($opt_key, $preset_config->get($opt_key))
                if $preset_config->has($opt_key);
        }
        ($preset->{default} || $preset->{external})
            ? $self->{btn_delete_preset}->Disable
            : $self->{btn_delete_preset}->Enable;
        
        $self->on_preset_loaded;
        $self->reload_values;
        $self->set_dirty(0);
        $Slic3r::GUI::Settings->{presets}{$self->name} = $preset->{file} ? basename($preset->{file}) : '';
    };
    if ($@) {
        $@ = "I was unable to load the selected config file: $@";
        Slic3r::GUI::catch_error($self);
        $self->select_default_preset;
    }
    
    Slic3r::GUI->save_settings;
}

sub get_preset_config {
    my $self = shift;
    my ($preset) = @_;
    
    if ($preset->{default}) {
        return Slic3r::Config->new_from_defaults(@{$self->{options}});
    } else {
        if (!-e $preset->{file}) {
            Slic3r::GUI::show_error($self, "The selected preset does not exist anymore ($preset->{file}).");
            return;
        }
        
        # apply preset values on top of defaults
        my $external_config = Slic3r::Config->load($preset->{file});
        my $config = Slic3r::Config->new;
        $config->set($_, $external_config->get($_))
            for grep $external_config->has($_), @{$self->{options}};
        
        return $config;
    }
}

sub add_options_page {
    my $self = shift;
    my ($title, $icon, %params) = @_;
    
    if ($icon) {
        my $bitmap = Wx::Bitmap->new("$Slic3r::var/$icon", wxBITMAP_TYPE_PNG);
        $self->{icons}->Add($bitmap);
        $self->{iconcount}++;
    }
    
    {
        # get all config options being added to the current page; remove indexes; associate defaults
        my @options = map { $_ =~ s/#.+//; $_ } grep !ref($_), map @{$_->{options}}, @{$params{optgroups}};
        my %defaults_to_set = map { $_ => 1 } @options;
        
        # apply default values for the options we don't have already
        delete $defaults_to_set{$_} for @{$self->{options}};
        $self->{config}->apply(Slic3r::Config->new_from_defaults(keys %defaults_to_set)) if %defaults_to_set;
        
        # append such options to our list
        push @{$self->{options}}, @options;
    }
    
    my $page = Slic3r::GUI::Tab::Page->new($self, $title, $self->{iconcount}, %params, on_change => sub {
        $self->on_value_change(@_);
        $self->set_dirty(1);
    });
    $page->Hide;
    $self->{sizer}->Add($page, 1, wxEXPAND | wxLEFT, 5);
    push @{$self->{pages}}, $page;
    $self->update_tree;
    return $page;
}

sub set_value {
    my $self = shift;
    my ($opt_key, $value) = @_;
    
    my $changed = 0;
    foreach my $page (@{$self->{pages}}) {
        $changed = 1 if $page->set_value($opt_key, $value);
    }
    return $changed;
}

sub reload_values {
    my $self = shift;
    
    $self->set_value($_, $self->{config}->get($_))
        for @{$self->{config}->get_keys};
}

sub update_tree {
    my $self = shift;
    my ($select) = @_;
    
    $select //= 0; #/
    
    my $rootItem = $self->{treectrl}->GetRootItem;
    $self->{treectrl}->DeleteChildren($rootItem);
    foreach my $page (@{$self->{pages}}) {
        my $itemId = $self->{treectrl}->AppendItem($rootItem, $page->{title}, $page->{iconID});
        $self->{treectrl}->SelectItem($itemId) if $self->{treectrl}->GetChildrenCount($rootItem) == $select + 1;
    }
}

sub set_dirty {
    my $self = shift;
    my ($dirty) = @_;

    return if $dirty and $self->is_dirty;
    return if (not $dirty) and (not $self->is_dirty);
    
    my $selection = $self->{presets_choice}->GetSelection;
    my $i = $self->{dirty} // $selection; #/
    my $text = $self->{presets_choice}->GetString($i);
    
    if ($dirty) {
        $self->{dirty} = $i;
        if ($text !~ / \(modified\)$/) {
            $self->{presets_choice}->SetString($i, "$text (modified)");
            $self->{presets_choice}->SetSelection($selection);  # http://trac.wxwidgets.org/ticket/13769
        }
    } else {
        $self->{dirty} = undef;
        $text =~ s/ \(modified\)$//;
        $self->{presets_choice}->SetString($i, $text);
        $self->{presets_choice}->SetSelection($selection);  # http://trac.wxwidgets.org/ticket/13769
    }
    $self->on_presets_changed;
}

sub is_dirty {
    my $self = shift;
    return (defined $self->{dirty});
}

sub load_presets {
    my $self = shift;
    
    $self->{presets} = [{
        default => 1,
        name    => '- default -',
    }];
    
    my %presets = Slic3r::GUI->presets($self->name);
    foreach my $preset_name (sort keys %presets) {
        push @{$self->{presets}}, {
            name => $preset_name,
            file => $presets{$preset_name},
        };
    }
    
    $self->{presets_choice}->Clear;
    $self->{presets_choice}->Append($_->{name}) for @{$self->{presets}};
    {
        # load last used preset
        my $i = first { basename($self->{presets}[$_]{file}) eq ($Slic3r::GUI::Settings->{presets}{$self->name} || '') } 1 .. $#{$self->{presets}};
        $self->{presets_choice}->SetSelection($i || 0);
        $self->on_select_preset;
    }
    $self->on_presets_changed;
}

sub load_config_file {
    my $self = shift;
    my ($file) = @_;
    
    # look for the loaded config among the existing menu items
    my $i = first { $self->{presets}[$_]{file} eq $file && $self->{presets}[$_]{external} } 1..$#{$self->{presets}};
    if (!$i) {
        my $preset_name = basename($file);  # keep the .ini suffix
        push @{$self->{presets}}, {
            file        => $file,
            name        => $preset_name,
            external    => 1,
        };
        $self->{presets_choice}->Append($preset_name);
        $i = $#{$self->{presets}};
    }
    $self->{presets_choice}->SetSelection($i);
    $self->on_select_preset;
    $self->on_presets_changed;
}

package Slic3r::GUI::Tab::Print;
use base 'Slic3r::GUI::Tab';

sub name { 'print' }
sub title { 'Print Settings' }

sub build {
    my $self = shift;
    
    $self->add_options_page('Layers and perimeters', 'layers.png', optgroups => [
        {
            title => 'Layer height',
            options => [qw(layer_height first_layer_height)],
        },
        {
            title => 'Vertical shells',
            options => [qw(perimeters spiral_vase)],
        },
        {
            title => 'Horizontal shells',
            options => [qw(top_solid_layers bottom_solid_layers)],
            lines => [
                {
                    label   => 'Solid layers',
                    options => [qw(top_solid_layers bottom_solid_layers)],
                },
            ],
        },
        {
            title => 'Quality (slower slicing)',
            options => [qw(extra_perimeters avoid_crossing_perimeters thin_walls overhangs)],
            lines => [
                Slic3r::GUI::OptionsGroup->single_option_line('extra_perimeters'),
                Slic3r::GUI::OptionsGroup->single_option_line('avoid_crossing_perimeters'),
                Slic3r::GUI::OptionsGroup->single_option_line('thin_walls'),
                Slic3r::GUI::OptionsGroup->single_option_line('overhangs'),
            ],
        },
        {
            title => 'Advanced',
            options => [qw(seam_position external_perimeters_first)],
        },
    ]);
    
    $self->add_options_page('Infill', 'shading.png', optgroups => [
        {
            title => 'Infill',
            options => [qw(fill_density fill_pattern solid_fill_pattern)],
        },
        {
            title => 'Reducing printing time',
            options => [qw(infill_every_layers infill_only_where_needed)],
        },
        {
            title => 'Advanced',
            options => [qw(solid_infill_every_layers fill_angle
                solid_infill_below_area only_retract_when_crossing_perimeters infill_first)],
        },
    ]);
    
    $self->add_options_page('Speed', 'time.png', optgroups => [
        {
            title => 'Speed for print moves',
            options => [qw(perimeter_speed small_perimeter_speed external_perimeter_speed infill_speed solid_infill_speed top_solid_infill_speed support_material_speed support_material_interface_speed bridge_speed gap_fill_speed)],
        },
        {
            title => 'Speed for non-print moves',
            options => [qw(travel_speed)],
        },
        {
            title => 'Modifiers',
            options => [qw(first_layer_speed)],
        },
        {
            title => 'Acceleration control (advanced)',
            options => [qw(perimeter_acceleration infill_acceleration bridge_acceleration first_layer_acceleration default_acceleration)],
        },
    ]);
    
    $self->add_options_page('Skirt and brim', 'box.png', optgroups => [
        {
            title => 'Skirt',
            options => [qw(skirts skirt_distance skirt_height min_skirt_length)],
        },
        {
            title => 'Brim',
            options => [qw(brim_width)],
        },
    ]);
    
    $self->add_options_page('Support material', 'building.png', optgroups => [
        {
            title => 'Support material',
            options => [qw(support_material support_material_threshold support_material_enforce_layers)],
        },
        {
            title => 'Raft',
            options => [qw(raft_layers)],
        },
        {
            title => 'Options for support material and raft',
            options => [qw(support_material_pattern support_material_spacing support_material_angle
                support_material_interface_layers support_material_interface_spacing
                dont_support_bridges)],
        },
    ]);
    
    $self->add_options_page('Notes', 'note.png', optgroups => [
        {
            title => 'Notes',
            no_labels => 1,
            options => [qw(notes)],
        },
    ]);
    
    $self->add_options_page('Output options', 'page_white_go.png', optgroups => [
        {
            title => 'Sequential printing',
            options => [qw(complete_objects extruder_clearance_radius extruder_clearance_height)],
            lines => [
                Slic3r::GUI::OptionsGroup->single_option_line('complete_objects'),
                {
                    label   => 'Extruder clearance (mm)',
                    options => [qw(extruder_clearance_radius extruder_clearance_height)],
                },
            ],
        },
        {
            title => 'Output file',
            options => [qw(gcode_comments output_filename_format)],
        },
        {
            title => 'Post-processing scripts',
            no_labels => 1,
            options => [qw(post_process)],
        },
    ]);
    
    $self->add_options_page('Multiple Extruders', 'funnel.png', optgroups => [
        {
            title => 'Extruders',
            options => [qw(perimeter_extruder infill_extruder support_material_extruder support_material_interface_extruder)],
        },
        {
            title => 'Ooze prevention',
            options => [qw(ooze_prevention standby_temperature_delta)],
        },
        {
            title => 'Advanced',
            options => [qw(interface_shells)],
        },
    ]);
    
    $self->add_options_page('Advanced', 'wrench.png', optgroups => [
        {
            title => 'Extrusion width',
            label_width => 180,
            options => [qw(extrusion_width first_layer_extrusion_width perimeter_extrusion_width infill_extrusion_width solid_infill_extrusion_width top_infill_extrusion_width support_material_extrusion_width)],
        },
        {
            title => 'Flow',
            options => [qw(bridge_flow_ratio)],
        },
        {
            title => 'Other',
            options => [($Slic3r::have_threads ? qw(threads) : ()), qw(resolution)],
        },
    ]);
}

sub hidden_options { !$Slic3r::have_threads ? qw(threads) : () }

package Slic3r::GUI::Tab::Filament;
use base 'Slic3r::GUI::Tab';

sub name { 'filament' }
sub title { 'Filament Settings' }

sub build {
    my $self = shift;
    
    $self->add_options_page('Filament', 'spool.png', optgroups => [
        {
            title => 'Filament',
            options => ['filament_diameter#0', 'extrusion_multiplier#0'],
        },
        {
            title => 'Temperature (°C)',
            options => ['temperature#0', 'first_layer_temperature#0', qw(bed_temperature first_layer_bed_temperature)],
            lines => [
                {
                    label   => 'Extruder',
                    options => ['first_layer_temperature#0', 'temperature#0'],
                },
                {
                    label   => 'Bed',
                    options => [qw(first_layer_bed_temperature bed_temperature)],
                },
            ],
        },
    ]);
    
    $self->add_options_page('Cooling', 'hourglass.png', optgroups => [
        {
            title => 'Enable',
            options => [qw(fan_always_on cooling)],
            lines => [
                Slic3r::GUI::OptionsGroup->single_option_line('fan_always_on'),
                Slic3r::GUI::OptionsGroup->single_option_line('cooling'),
                {
                    label => '',
                    widget => ($self->{description_line} = Slic3r::GUI::OptionsGroup::StaticTextLine->new),
                },
            ],
        },
        {
            title => 'Fan settings',
            options => [qw(min_fan_speed max_fan_speed bridge_fan_speed disable_fan_first_layers)],
            lines => [
                {
                    label   => 'Fan speed',
                    options => [qw(min_fan_speed max_fan_speed)],
                },
                Slic3r::GUI::OptionsGroup->single_option_line('bridge_fan_speed'),
                Slic3r::GUI::OptionsGroup->single_option_line('disable_fan_first_layers'),
            ],
        },
        {
            title => 'Cooling thresholds',
            label_width => 250,
            options => [qw(fan_below_layer_time slowdown_below_layer_time min_print_speed)],
        },
    ]);
}

sub _update_description {
    my $self = shift;
    
    my $config = $self->config;
    
    my $msg = "";
    my $fan_other_layers = $config->fan_always_on
        ? sprintf "will always run at %d%%%s.", $config->min_fan_speed,
                ($config->disable_fan_first_layers > 1
                    ? " except for the first " . $config->disable_fan_first_layers . " layers"
                    : $config->disable_fan_first_layers == 1
                        ? " except for the first layer"
                        : "")
        : "will be turned off.";
    
    if ($config->cooling) {
        $msg = sprintf "If estimated layer time is below ~%ds, fan will run at %d%% and print speed will be reduced so that no less than %ds are spent on that layer (however, speed will never be reduced below %dmm/s).",
            $config->slowdown_below_layer_time, $config->max_fan_speed, $config->slowdown_below_layer_time, $config->min_print_speed;
        if ($config->fan_below_layer_time > $config->slowdown_below_layer_time) {
            $msg .= sprintf "\nIf estimated layer time is greater, but still below ~%ds, fan will run at a proportionally decreasing speed between %d%% and %d%%.",
                $config->fan_below_layer_time, $config->max_fan_speed, $config->min_fan_speed;
        }
        $msg .= "\nDuring the other layers, fan $fan_other_layers"
    } else {
        $msg = "Fan $fan_other_layers";
    }
    $self->{description_line}->SetText($msg);
}

sub on_value_change {
    my $self = shift;
    my ($opt_key) = @_;
    $self->SUPER::on_value_change(@_);
    
    $self->_update_description;
}

package Slic3r::GUI::Tab::Printer;
use base 'Slic3r::GUI::Tab';

sub name { 'printer' }
sub title { 'Printer Settings' }

sub build {
    my $self = shift;
    
    $self->{extruders_count} = 1;
    
    $self->add_options_page('General', 'printer_empty.png', optgroups => [
        {
            title => 'Size and coordinates',
            options => [qw(bed_size print_center z_offset)],
        },
        {
            title => 'Firmware',
            options => [qw(gcode_flavor use_relative_e_distances)],
        },
        {
            class => 'Slic3r::GUI::OptionsGroup',
            title => 'Capabilities',
            options => [
                {
                    opt_key => 'extruders_count',
                    label   => 'Extruders',
                    tooltip => 'Number of extruders of the printer.',
                    type    => 'i',
                    min     => 1,
                    default => 1,
                    on_change => sub { $self->{extruders_count} = $_[0] },
                },
            ],
        },
        {
            title => 'Advanced',
            options => [qw(use_firmware_retraction vibration_limit)],
        },
    ]);
    
    $self->add_options_page('Custom G-code', 'cog.png', optgroups => [
        {
            title => 'Start G-code',
            no_labels => 1,
            options => [qw(start_gcode)],
        },
        {
            title => 'End G-code',
            no_labels => 1,
            options => [qw(end_gcode)],
        },
        {
            title => 'Layer change G-code',
            no_labels => 1,
            options => [qw(layer_gcode)],
        },
        {
            title => 'Tool change G-code',
            no_labels => 1,
            options => [qw(toolchange_gcode)],
        },
    ]);
    
    $self->{extruder_pages} = [];
    $self->_build_extruder_pages;
}

sub _extruder_options { qw(nozzle_diameter extruder_offset retract_length retract_lift retract_speed retract_restart_extra retract_before_travel wipe
    retract_layer_change retract_length_toolchange retract_restart_extra_toolchange) }

sub _build_extruder_pages {
    my $self = shift;
    
    my $default_config = Slic3r::Config::Full->new;
    
    foreach my $extruder_idx (@{$self->{extruder_pages}} .. $self->{extruders_count}-1) {
        # extend options
        foreach my $opt_key ($self->_extruder_options) {
            my $values = $self->{config}->get($opt_key);
            if (!defined $values) {
                $values = [ $default_config->get_at($opt_key, 0) ];
            } else {
                # use last extruder's settings for the new one
                my $last_value = $values->[-1];
                $values->[$extruder_idx] //= $last_value;
            }
            $self->{config}->set($opt_key, $values)
                or die "Unable to extend $opt_key";
        }
        
        # build page
        $self->{extruder_pages}[$extruder_idx] = $self->add_options_page("Extruder " . ($extruder_idx + 1), 'funnel.png', optgroups => [
            {
                title => 'Size',
                options => ['nozzle_diameter#' . $extruder_idx],
            },
            {
                title => 'Position (for multi-extruder printers)',
                options => ['extruder_offset#' . $extruder_idx],
            },
            {
                title => 'Retraction',
                options => [
                    map "${_}#${extruder_idx}",
                        qw(retract_length retract_lift retract_speed retract_restart_extra retract_before_travel retract_layer_change wipe)
                ],
            },
            {
                title => 'Retraction when tool is disabled (advanced settings for multi-extruder setups)',
                options => [
                    map "${_}#${extruder_idx}",
                        qw(retract_length_toolchange retract_restart_extra_toolchange)
                ],
            },
        ]);
        $self->{extruder_pages}[$extruder_idx]{disabled} = 0;
    }
    
    # remove extra pages
    if ($self->{extruders_count} <= $#{$self->{extruder_pages}}) {
        splice @{$self->{extruder_pages}}, $self->{extruders_count};
    }
    
    # remove extra config values
    foreach my $opt_key ($self->_extruder_options) {
        my $values = $self->{config}->get($opt_key);
        splice @$values, $self->{extruders_count} if $self->{extruders_count} <= $#$values;
        $self->{config}->set($opt_key, $values)
            or die "Unable to truncate $opt_key";
    }
    
    # rebuild page list
    @{$self->{pages}} = (
        (grep $_->{title} !~ /^Extruder \d+/, @{$self->{pages}}),
        @{$self->{extruder_pages}}[ 0 .. $self->{extruders_count}-1 ],
    );
}

sub on_value_change {
    my $self = shift;
    my ($opt_key) = @_;
    $self->SUPER::on_value_change(@_);
    
    if ($opt_key eq 'extruders_count') {
        # add extra pages or remove unused
        $self->_build_extruder_pages;
        
        # update page list and select first page (General)
        $self->update_tree(0);
    }
}

# this gets executed after preset is loaded and before GUI fields are updated
sub on_preset_loaded {
    my $self = shift;
    
    # update the extruders count field
    {
        # update the GUI field according to the number of nozzle diameters supplied
        $self->set_value('extruders_count', scalar @{ $self->{config}->nozzle_diameter });
        
        # update extruder page list
        $self->on_value_change('extruders_count');
    }
}

sub load_config_file {
    my $self = shift;
    $self->SUPER::load_config_file(@_);
    
    Slic3r::GUI::warning_catcher($self)->(
        "Your configuration was imported. However, Slic3r is currently only able to import settings "
        . "for the first defined filament. We recommend you don't use exported configuration files "
        . "for multi-extruder setups and rely on the built-in preset management system instead.")
        if @{ $self->{config}->nozzle_diameter } > 1;
}

package Slic3r::GUI::Tab::Page;
use Wx qw(:misc :panel :sizer);
use base 'Wx::ScrolledWindow';

sub new {
    my $class = shift;
    my ($parent, $title, $iconID, %params) = @_;
    my $self = $class->SUPER::new($parent, -1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
    $self->{optgroups}  = [];
    $self->{title}      = $title;
    $self->{iconID}     = $iconID;
    
    $self->SetScrollbars(1, 1, 1, 1);
    
    $self->{vsizer} = Wx::BoxSizer->new(wxVERTICAL);
    $self->SetSizer($self->{vsizer});
    
    if ($params{optgroups}) {
        $self->append_optgroup(
            %$_,
            config      => $parent->{config},
            on_change   => $params{on_change},
        ) for @{$params{optgroups}};
    }
    
    return $self;
}

sub append_optgroup {
    my $self = shift;
    my %params = @_;
    
    my $class = $params{class} || 'Slic3r::GUI::ConfigOptionsGroup';
    my $optgroup = $class->new(
        parent      => $self,
        config      => $self->GetParent->{config},
        label_width => 200,
        %params,
    );
    $self->{vsizer}->Add($optgroup->sizer, 0, wxEXPAND | wxALL, 5);
    push @{$self->{optgroups}}, $optgroup;
}

sub set_value {
    my $self = shift;
    my ($opt_key, $value) = @_;
    
    my $changed = 0;
    foreach my $optgroup (@{$self->{optgroups}}) {
        $changed = 1 if $optgroup->set_value($opt_key, $value);
    }
    return $changed;
}

package Slic3r::GUI::SavePresetWindow;
use Wx qw(:combobox :dialog :id :misc :sizer);
use Wx::Event qw(EVT_BUTTON EVT_TEXT_ENTER);
use base 'Wx::Dialog';

sub new {
    my $class = shift;
    my ($parent, %params) = @_;
    my $self = $class->SUPER::new($parent, -1, "Save preset", wxDefaultPosition, wxDefaultSize);
    
    my @values = grep $_ ne '- default -', @{$params{values}};
    
    my $text = Wx::StaticText->new($self, -1, "Save " . lc($params{title}) . " as:", wxDefaultPosition, wxDefaultSize);
    $self->{combo} = Wx::ComboBox->new($self, -1, $params{default}, wxDefaultPosition, wxDefaultSize, \@values,
                                       wxTE_PROCESS_ENTER);
    my $buttons = $self->CreateStdDialogButtonSizer(wxOK | wxCANCEL);
    
    my $sizer = Wx::BoxSizer->new(wxVERTICAL);
    $sizer->Add($text, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, 10);
    $sizer->Add($self->{combo}, 0, wxEXPAND | wxLEFT | wxRIGHT, 10);
    $sizer->Add($buttons, 0, wxEXPAND | wxBOTTOM | wxLEFT | wxRIGHT, 10);
    
    EVT_BUTTON($self, wxID_OK, \&accept);
    EVT_TEXT_ENTER($self, $self->{combo}, \&accept);
    
    $self->SetSizer($sizer);
    $sizer->SetSizeHints($self);
    
    return $self;
}

sub accept {
    my ($self, $event) = @_;

    if (($self->{chosen_name} = $self->{combo}->GetValue)) {
        if ($self->{chosen_name} !~ /^[^<>:\/\\|?*\"]+$/i) {
            Slic3r::GUI::show_error($self, "The supplied name is not valid; the following characters are not allowed: <>:/\|?*\"");
        } elsif ($self->{chosen_name} eq '- default -') {
            Slic3r::GUI::show_error($self, "The supplied name is not available.");
        } else {
            $self->EndModal(wxID_OK);
        }
    }
}

sub get_name {
    my $self = shift;
    return $self->{chosen_name};
}

1;