Wrangler/Wx/FileBrowser.pm untested

filter: Statementstmt 0.0% 0 / 951 Branchbran 0.0% 0 / 338 Conditioncond 0.0% 0 / 95 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 50 Podpod 0.0% 0 / 39 totaltotal 0.0% 0 / 1473 CC 170 SCAR 50.4
CC
170
Cov
0%
Populate
462.0
Delete
342.0
OnChar
272.0
CRAP 154.0
1 package Wrangler::Wx::FileBrowser;
2  
3 use strict;
4 use warnings;
5  
6 use Wx qw(:everything);
7 use Wx::Event qw(:everything);
8 use Wx::DND; # offers wxTheClipboard
9 use base qw(Wx::ListCtrl);
10 use HTTP::Date ();
11 use Encode;
12  
13 sub new {
14 my $class = shift;
15 my $parent = shift;
16 my $self = $class->SUPER::new( $parent, -1, wxDefaultPosition, wxDefaultSize,
17 wxLC_REPORT | wxLC_EDIT_LABELS | wxSUNKEN_BORDER
18 );
19  
20 # hook-up access to $wrangler
21 $self->{wrangler} = $parent->{wrangler};
22  
23 # imagelist is set-up centrally in Main; link data structures here
24 $self->SetImageList( ${ $parent->{imagelist} }, wxIMAGE_LIST_SMALL );
25 $self->{images} = $parent->{images};
26  
27 $self->SetForegroundColour(Wx::Colour->new(@{ $self->{wrangler}->config()->{'ui.foreground_colour'} })) if $self->{wrangler}->config()->{'ui.foreground_colour'};
28  
29 ## to mediate between begin/end routines, we use a small internal stash
30 $self->{our_stash} = undef;
31  
32 $self->Columns();
33 (my $richlist,$self->{current_dir}) = $self->{wrangler}->{fs}->richlist( $self->{wrangler}->{fs}->cwd(), Wrangler::wishlist() );
34 $self->sort_richlist($richlist);
35 $self->Populate($richlist);
36  
37 # anything supplied via CLI?
38 my $start_dir = $Wrangler::Config::env{CLI_ChangeDirectory} ? $Wrangler::Config::env{CLI_ChangeDirectory} : $self->{wrangler}->{fs}->cwd();
39  
40 # emit appropriate event
41 Wrangler::PubSub::publish('dir.activated', $start_dir );
42 $self->{wrangler}->{current_dir} = $start_dir; # a race-condition seems to be preventing global current_dir in Wrangler to be populated right after startup, so we need this hack; with multiple FileBrowser widget, last-wins
43  
44 # $self->SetFocus();
45  
46 ## our custom FileBrowser events
47 # To a certain extend, the filebrowser widgets 'know' about what they are
48 # displaying and as such, they emit less generic, more meningful events
49 # Note that we don't use these events here, although we could, for example
50 # for "local action", like what needs to be done when "a directory is activated".
51 # That's because these Events are meant for other widgets, to which we send
52 # a bit of information, but not things like the TreeEvent which is mostly
53 # specific to the local widget and would be send around the app without use.
54 Wrangler::PubSub::subscribe('dir.activated', sub { Wrangler::debug("OnDirActivated: @_"); $self->ChangeDirectory($_[0]); },__PACKAGE__);
55 Wrangler::PubSub::subscribe('filebrowser.refresh', sub { # triggered after settings for this widget have changed
56 Wrangler::debug("OnRefresh: @_");
57 $self->RePopulate();
58 },__PACKAGE__);
59 Wrangler::PubSub::subscribe('filebrowser.refresh.all', sub { # triggered after column-settings for this widget have changed
60 Wrangler::debug("OnRefreshAll: @_");
61 $self->ClearAll(); # delete all items and all columns
62 $self->Columns();
63 $self->RePopulate();
64 },__PACKAGE__);
65 Wrangler::PubSub::subscribe('filebrowser.selection_move.up', sub { # used to remotely move selection; used by FormEditor
66 $self->SelectionMoveUp(@_);
67 },__PACKAGE__);
68 Wrangler::PubSub::subscribe('filebrowser.selection_move.down', sub { # used to remotely move selection; used by FormEditor
69 $self->SelectionMoveDown(@_);
70 },__PACKAGE__);
71 Wrangler::PubSub::subscribe('zoom.in', sub {
72 Wrangler::debug("OnZoomIn: @_");
73  
74 my $size = $self->GetFont()->GetPointSize() + 1;
75 Wrangler::debug(" SetFont: $size");
76 $self->SetFont( Wx::Font->new( $size, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL) );
77 $self->Update();
78 $self->{wrangler}->config()->{'ui.filebrowser.font_size'} = $size;
79 },__PACKAGE__);
80 Wrangler::PubSub::subscribe('zoom.out', sub {
81 Wrangler::debug("OnZoomOut: @_");
82  
83 my $size = $self->GetFont()->GetPointSize() - 1;
84 Wrangler::debug(" SetFont: $size");
85 $self->SetFont( Wx::Font->new( $size, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL) );
86 $self->Update();
87 $self->{wrangler}->config()->{'ui.filebrowser.font_size'} = $size;
88 },__PACKAGE__);
89 Wrangler::PubSub::subscribe('zoom.standard', sub {
90 Wrangler::debug("OnZoomStandard: @_");
91  
92 my $size = 9;
93 Wrangler::debug(" SetFont: $size");
94 $self->SetFont( Wx::Font->new( $size, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL) );
95 $self->Update();
96 $self->{wrangler}->config()->{'ui.filebrowser.font_size'} = $size;
97 },__PACKAGE__);
98  
99 ## WxPerl ListCtrl events
100 EVT_LIST_BEGIN_DRAG($self, $self, sub {
101 Wrangler::debug("OnBeginDrag: @_");
102 # my $source = Wx::DropSource->new( $self );
103 # # $source->SetData( $self->GetSelections_as_FileDataObject() );
104 # $source->SetData( $self->GetSelections_as_CompositeDataObject() );
105 # $source->DoDragDrop(1);
106 });
107 #Begin dragging with the left mouse button. Processes a wxEVT_COMMAND_LIST_BEGIN_DRAG event type.
108 EVT_LIST_BEGIN_RDRAG($self, $self, sub { Wrangler::debug("OnBeginRDrag: @_"); });
109 #Begin dragging with the right mouse button. Processes a wxEVT_COMMAND_LIST_BEGIN_RDRAG event type.
110 # EVT_BEGIN_LABEL_EDIT($self, $self, sub { Wrangler::debug("OnBeginLabelEdit: @_"); });
111 #Begin editing a label. This can be prevented by calling Veto(). Processes a wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT event type.
112 EVT_LIST_END_LABEL_EDIT($self, $self, sub { Wrangler::debug("OnEndLabelEdit: @_"); OnEndLabelEdit(@_); });
113 #Finish editing a label. This can be prevented by calling Veto(). Processes a wxEVT_COMMAND_LIST_END_LABEL_EDIT event type.
114 EVT_LIST_DELETE_ITEM($self, $self, sub { Wrangler::debug("OnDeleteItem: @_"); });
115 #An item was deleted. Processes a wxEVT_COMMAND_LIST_DELETE_ITEM event type.
116 EVT_LIST_DELETE_ALL_ITEMS($self, $self, sub { Wrangler::debug("OnDeleteAllItems: @_"); });
117 #All items were deleted. Processes a wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS event type.
118 EVT_LIST_ITEM_SELECTED($self, $self, sub {
119 # collapse SelectAll into one event, emitted in SelectAll()
120 if($self->{our_stash}->{ignore_selected}){
121 Wrangler::debug("OnItemSelected: (ignored, SelectAll) @_");
122 delete($self->{our_stash}->{ignore_selected});
123 return;
124 }
125  
126 my $selections = $_[0]->GetSelections_as_richlist_items();
127  
128 # ignore re-selects of same item
129 if( $self->{current_selection}
130 && scalar(@{$self->{current_selection}}) == 1
131 && scalar(@{$self->{current_selection}}) == scalar(@$selections)
132 && $self->{current_selection}->[0]->{_itemId} == $selections->[0]->{_itemId}
133 ){
134 Wrangler::debug("OnItemSelected: (ignored, is same) @_");
135 return;
136 }
137  
138 Wrangler::debug("OnItemSelected (changed): @_");
139 $self->{current_selection} = $selections;
140 Wrangler::PubSub::publish('selection.changed', scalar(@$selections), $selections );
141 });
142 # EVT_LEFT_UP($self, sub { Wrangler::debug("OnLeftUp: @_"); });
143 # EVT_KEY_UP($self, sub { Wrangler::debug("OnKeyUp: @_"); });
144 # The item has been selected. Means 'is done' thus can't be vetoed. Processes a wxEVT_COMMAND_LIST_ITEM_SELECTED event type.
145 EVT_LIST_ITEM_DESELECTED($self, $self, sub { Wrangler::debug("OnItemDeselected: @_"); });
146 #The item has been deselected. Processes a wxEVT_COMMAND_LIST_ITEM_DESELECTED event type.
147 EVT_LIST_ITEM_ACTIVATED($self, $self, sub { OnActivated(@_); });
148 #The item has been activated (ENTER or double click). Processes a wxEVT_COMMAND_LIST_ITEM_ACTIVATED event type.
149 EVT_LIST_ITEM_FOCUSED($self, $self, sub { Wrangler::debug("OnItemFocused: @_"); });
150 #The currently focused item has changed. Processes a wxEVT_COMMAND_LIST_ITEM_FOCUSED event type.
151 # EVT_LIST_ITEM_MIDDLE_CLICK($self, $self, sub { Wrangler::debug("On: @_"); });
152 #The middle mouse button has been clicked on an item. This is only supported by the generic control. Processes a wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK event type.
153 EVT_LIST_ITEM_RIGHT_CLICK($self, $self, sub { Wrangler::debug("OnRightClick: @_"); OnRightClick(@_); });
154 #The right mouse button has been clicked on an item. Processes a wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK event type.
155 EVT_LIST_KEY_DOWN($self, $self, sub { Wrangler::debug("OnKeyDown: @_"); });
156 #A key has been pressed. Processes a wxEVT_COMMAND_LIST_KEY_DOWN event type.
157 #silent EVT_LIST_INSERT_ITEM($self, $self, sub { Wrangler::debug("OnInsertItem: @_"); });
158 #An item has been inserted. Processes a wxEVT_COMMAND_LIST_INSERT_ITEM event type.
159 EVT_LIST_COL_CLICK($self, $self, sub {
160 Wrangler::debug("OnColClick: @_");
161  
162 # toggle sort order
163 $self->{sort_column} = $_[1]->GetColumn;
164 $self->{sort_order} = $self->{sort_order} && $self->{sort_order} eq 'DESC' ? 'ASC' : 'DESC';
165  
166 # remember sorting
167 my $config = $self->{wrangler}->config();
168 my $sort_on = $self->column_key($self->{sort_column});
169 if( $config->{'ui.filebrowser.sorting.per_directory'} ){
170 $config->{'ui.filebrowser.sort'}->{ $self->{current_dir} } = [$self->{sort_order}, $sort_on];
171 }else{
172 $config->{'ui.filebrowser.sort'} = [$self->{sort_order}, $sort_on];
173 }
174  
175 Wrangler::debug("OnColClick: sort_column:". $self->{sort_column} .' = sort_on:'. $sort_on .', sort_order:'. $self->{sort_order} );
176  
177 $self->RePopulate();
178 });
179 #A column (m_col) has been left-clicked. Processes a wxEVT_COMMAND_LIST_COL_CLICK event type.
180 EVT_LIST_COL_RIGHT_CLICK($self, $self, sub { Wrangler::debug("OnColRightClick: @_");
181 Wrangler::PubSub::publish('show.settings', 1, 2);
182 });
183 #A column (m_col) has been right-clicked. Processes a wxEVT_COMMAND_LIST_COL_RIGHT_CLICK event type.
184 EVT_LIST_COL_BEGIN_DRAG($self, $self, sub { Wrangler::debug("OnColBeginDrag: @_"); });
185 #The user started resizing a column - can be vetoed. Processes a wxEVT_COMMAND_LIST_COL_BEGIN_DRAG event type.
186 EVT_LIST_COL_DRAGGING($self, $self, sub { Wrangler::debug("OnColDragging: @_"); });
187 #The divider between columns is being dragged. Processes a wxEVT_COMMAND_LIST_COL_DRAGGING event type.
188 EVT_LIST_COL_END_DRAG($self, $self, sub {
189 Wrangler::debug("OnColEndDrag: @_");
190  
191 my $col = $_[1]->GetColumn();
192 my $newwidth = $_[0]->GetColumnWidth($col);
193 $self->{columns}->[$col]->{width} = $newwidth;
194  
195 ## update our hit->col index, used in GetColumn()
196 $self->{columns_widths_index} = [0];
197 my $accumulated_width;
198 for (0 .. $#{ $self->{columns} }){
199 $accumulated_width += ${ $self->{columns} }[$_]->{width};
200 push(@{ $self->{columns_widths_index} }, $accumulated_width);
201 }
202  
203 # Wrangler::debug(" column: $col, width:$newwidth");
204 });
205 #A column has been resized by the user. Processes a wxEVT_COMMAND_LIST_COL_END_DRAG event type.
206 EVT_LIST_CACHE_HINT($self, $self, sub { Wrangler::debug("OnListCacheHint: @_"); });
207 #Prepare cache for a virtual list control. Processes a wxEVT_COMMAND_LIST_CACHE_HINT event type.
208  
209 EVT_CHAR( $self, \&OnChar );
210 EVT_PAINT($self, sub {
211 # Wrangler::debug("OnPaint: @_");
212 # $self->OptimiseColumns();
213 });
214 EVT_SIZE($self, sub {
215 # Wrangler::debug("OnSize: @_");
216 # $self->OptimiseColumns(1);
217 $_[1]->Skip(1);
218 });
219  
220 ## until Wx 2.9.1 and its wxFileSystemWatcher arrives, we use our own simple (pull) monitoring
221 $self->{timer} = Wx::Timer->new();
222 EVT_TIMER($self->{timer}, $self->{timer}, sub {
223 my $richprop_dir = $self->{wrangler}->{fs}->richproperties($self->{current_dir}, ['Filesystem::Modified']);
224  
225 return if $self->{our_stash}->{rename}; # don't disturb ongoing renames
226  
227 if($richprop_dir->{'Filesystem::Modified'} != $self->{current_dir_mtime}){
228 Wrangler::debug("Wrangler::Wx::FileBrowser: Timer pull_monitor: $self->{current_dir} $self->{current_dir_mtime} changed");
229 $self->{current_dir_mtime} = $richprop_dir->{'Filesystem::Modified'};
230 $self->RePopulate();
231 }else{
232 # Wrangler::debug("Wrangler::Wx::FileBrowser: Timer pull_monitor: $self->{current_dir} $self->{current_dir_mtime}");
233 }
234 });
235  
236 return $self;
237 }
238  
239 sub Clear {
240 my ($filebrowser) = @_;
241  
242 $filebrowser->Show( 0 );
243 $filebrowser->DeleteAllItems();
244 $filebrowser->Show( 1 );
245 }
246  
247 sub OptimiseColumns {
248 my $filebrowser = shift;
249 my $force = shift;
250 return if !$force && $filebrowser->{columns_optimised};
251  
252 ## optimise column width
253 # my $width = $filebrowser->GetViewRect()->width; # is completely off
254 my $width = $filebrowser->GetClientSize()->width;
255 # my $width_userdefined;
256 # for(@{ $filebrowser->{columns} }){
257 # $width_userdefined += $_->{width};
258 # }
259 my $width_half = int( ($width + 50) / 2); # +50 to compensate for $width being too small
260 $filebrowser->SetColumnWidth (0, $width_half );
261  
262 my $colCnt = $filebrowser->GetColumnCount();
263 Wrangler::debug("OptimiseColumns: width:$width; width_half:$width_half; colCnt:$colCnt");
264 for(1 .. $colCnt){
265 $filebrowser->SetColumnWidth($_, int( $width_half / $colCnt ) );
266 }
267 $filebrowser->{columns_optimised} = 1;
268 }
269  
270 ## who should know about sorting, Wx, the vfs, or wrangler? Wx is only presentation,
271 ## so 'No'; the vfs is like fuse or the raw fs: no idea of sorting; and as expected,
272 ## it's wrangler who does the sorting, so this is a helper offered by wrangler that
273 ## can handle richlists, and does sorting like people expect it in a file-listing
274 my $regex_numeric = qr/^\d+$/;
275 sub sort_richlist {
276 my $filebrowser = shift;
277 my $richlist = shift;
278  
279 my %config = %{ $filebrowser->{wrangler}->config() }; # fewer lookups
280  
281 ## logic: 1. config, 2. default
282 my %args = ( sort_on => 'Filesystem::Filename', sort_order => 'ASC' );
283 if($config{'ui.filebrowser.sort'}){
284 if(ref($config{'ui.filebrowser.sort'}) eq 'HASH'){
285 if( my $ref = $config{'ui.filebrowser.sort'}->{ $filebrowser->{current_dir} } ){
286 $args{sort_order} = $config{'ui.filebrowser.sort'}->{ $filebrowser->{current_dir} }->[0];
287 $args{sort_on} = $config{'ui.filebrowser.sort'}->{ $filebrowser->{current_dir} }->[1];
288 }
289 }elsif(ref($config{'ui.filebrowser.sort'}) eq 'ARRAY'){
290 $args{sort_order} = $config{'ui.filebrowser.sort'}->[0];
291 $args{sort_on} = $config{'ui.filebrowser.sort'}->[1];
292 }
293 # sort_richlist is called very early, and this logic here, is also used
294 # to kind-of init a "current sorting" notion, which is needed for how
295 # on col click currently works/ to react correctly on first click
296 $filebrowser->{sort_order} = $args{sort_order};
297 }
298 my ($sort_order,$sort_on) = ($args{sort_order},$args{sort_on});
299  
300 ## separate types ; this is how we currently implement the two-level
301 ## sorting of 'on types' first, then 'by name'
302 ## we treat updir separately, so it's always first, sorting is still not perfect, as dotfiles
303 ## come after files starting with ! for example, should probably be the other way 'round
304 my (@devices,@updir,@dirs,@files);
305 my $data_type = 'numeric';
306 for(@$richlist){
307 if($_->{'Filesystem::Type'} eq 'Directory'){
308 if(!@updir && $_->{'Filesystem::Filename'} eq '..'){
309 push(@updir, $_);
310 }else{
311 push(@dirs, $_);
312 }
313 }elsif($_->{'Filesystem::Type'} eq 'File'){
314 push(@files, $_);
315 }else{
316 push(@devices, $_);
317 }
318 $data_type = 'alphanumeric' unless $_->{ $sort_on } =~ $regex_numeric;
319 }
320 @$richlist = ();
321  
322 Wrangler::debug("FileBrowser::sort_richlist: sort_on:$sort_on, sort_order:$sort_order, data_type:$data_type");
323  
324 if($data_type eq 'numeric'){
325 # numeric
326 if($sort_order eq 'DESC'){
327 @dirs = sort { $b->{ $sort_on } <=> $a->{ $sort_on } } @dirs;
328 push(@dirs,@updir);
329 @files = sort { $b->{ $sort_on } <=> $a->{ $sort_on } } @files;
330 }else{
331 @dirs = sort { $a->{ $sort_on } <=> $b->{ $sort_on } } @dirs;
332 unshift(@dirs,@updir);
333 @files = sort { $a->{ $sort_on } <=> $b->{ $sort_on } } @files;
334 }
335 }else{
336 # alphanumeric
337 if($sort_order eq 'DESC'){
338 @dirs = sort { lc($b->{ $sort_on }) cmp lc($a->{ $sort_on }) } @dirs;
339 push(@dirs,@updir);
340 @files = sort { lc($b->{ $sort_on }) cmp lc($a->{ $sort_on }) } @files;
341 }else{
342 @dirs = sort { lc($a->{ $sort_on }) cmp lc($b->{ $sort_on }) } @dirs;
343 unshift(@dirs,@updir);
344 @files = sort { lc($a->{ $sort_on }) cmp lc($b->{ $sort_on }) } @files;
345 }
346 }
347  
348 @$richlist = (@devices,@dirs,@files);
349  
350 return $richlist;
351 }
352  
353 sub column_count {
354 return $#{ $_[0]->{columns} };
355 }
356 sub column_key {
357 # Wrangler::debug("column_key: $_[0], $_[1]");
358 return ${ $_[0]->{columns} }[ $_[1] ]->{value_from};
359 }
360  
361 sub SetOurItemData {
362 Wrangler::debug("SetOurItemData: warning: not enough arguments passed") unless @_ == 3;
363 ${ $_[0]->{ItemData} }[ $_[1] ] = $_[2];
364 }
365  
366 sub GetOurItemData {
367 Wrangler::debug("GetOurItemData: warning: not enough arguments passed") unless @_ == 2;
368 Wrangler::debug("GetOurItemData: warning: item $_[1] is not defined!") unless defined(${ $_[0]->{ItemData} }[ $_[1] ]);
369 return ${ $_[0]->{ItemData} }[ $_[1] ];
370 }
371  
372 sub DeleteAllOurItemData {
373 $_[0]->{ItemData} = [];
374 }
375  
376 # a helper sub to get more in line with TreeListCtrl
377 sub GetSelections {
378 return () unless $_[0]->GetSelectedItemCount(); # untested optimisation
379  
380 my @selections;
381 my $currId = -1;
382 for(;;){
383 $currId = $_[0]->GetNextItem($currId, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
384 if($currId == -1){
385 last;
386 }else{
387 push(@selections, $currId);
388 }
389 }
390  
391 return wantarray ? @selections : \@selections;
392 }
393  
394 sub GetSelections_as_richlist_items {
395 my $selections = $_[0]->GetSelections();
396  
397 return wantarray ? () : [] unless ref($selections) && @$selections;
398  
399 for (@$selections){
400 my $itemId = $_;
401 my $richlist_item = $_[0]->GetOurItemData( $_[0]->GetItem($_)->GetData() ); # GetOurItemData returns the actual data, no ->GetData needed
402 $_ = $richlist_item; # $_ = { itemId => $_, richlist_item => $richlist_item };
403 $_->{_itemId} = $_; # used to identify if selections are the same, in event _SELECTION_CHANGED
404 }
405  
406 return wantarray ? @$selections : $selections;
407 }
408  
409 sub GetSelections_as_FileDataObject {
410 my $filebrowser = shift;
411  
412 ## create and fill the FileDataObject with full file-path for each selected item
413 my $fdo = Wx::FileDataObject->new();
414 for my $currId ($filebrowser->GetSelections){
415 my $richlist_item = $filebrowser->GetOurItemData( $filebrowser->GetItem($currId)->GetData() ); # GetOurItemData returns the actual data, no ->GetData needed
416 # Wrangler::debug("- $richlist_item->{'Filesystem::Path'} ");
417 $fdo->AddFile( $richlist_item->{'Filesystem::Path'} );
418 }
419  
420 return $fdo;
421 }
422  
423 sub GetSelections_as_CompositeDataObject {
424 my $cdo = Wx::DataObjectComposite->new();
425 $cdo->Add( $_[0]->GetSelections_as_FileDataObject() );
426  
427 return $cdo;
428 }
429  
430 sub SelectAll {
431 my $filebrowser = shift;
432  
433 my $cnt = $filebrowser->GetItemCount;
434 for( 0 .. ($cnt - 1) ){
435 if($_ == 0){
436 next if $filebrowser->GetItemText($_) eq '..';
437 }
438 $filebrowser->{our_stash}->{ignore_selected} = 1; # resetted in EVT_ITEM_SELECTED
439 $filebrowser->SetItemState( $_, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
440 }
441  
442 Wrangler::debug("SelectAll: emitting 'selection.changed' event");
443 my $selections = $filebrowser->GetSelections_as_richlist_items();
444 Wrangler::PubSub::publish('selection.changed', scalar(@$selections), $selections );
445 }
446  
447 sub DeselectAll {
448 my $filebrowser = shift;
449  
450 my $cnt = $filebrowser->GetItemCount;
451 for( 0 .. ($cnt - 1) ){
452 $filebrowser->SetItemState( $_, 0, wxLIST_STATE_SELECTED );
453 }
454  
455 Wrangler::debug("DeselectAll: emitting 'selection.changed' event");
456 Wrangler::PubSub::publish('selection.changed', 0 );
457 }
458  
459 sub InvertSelections {
460 my $filebrowser = shift;
461  
462 my $cnt = $filebrowser->GetItemCount;
463 for( 0 .. ($cnt - 1) ){
464 if($_ == 0){
465 next if $filebrowser->GetItemText($_) eq '..';
466 }
467  
468 my $state = $filebrowser->GetItemState( $_, wxLIST_STATE_SELECTED );
469  
470 if($state == wxLIST_STATE_SELECTED){
471 $filebrowser->SetItemState( $_, 0, wxLIST_STATE_SELECTED );
472 }else{
473 $filebrowser->SetItemState( $_, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
474 }
475 }
476  
477 my $selections = $filebrowser->GetSelections_as_richlist_items();
478 Wrangler::PubSub::publish('selection.changed', scalar(@$selections), $selections );
479 }
480  
481 sub SelectionMoveUp {
482 my $filebrowser = shift;
483 my $event = shift;
484  
485 Wrangler::debug('FileBrowser::SelectionMoveUp: ');
486  
487 if($filebrowser->GetSelectedItemCount() == 0){
488 # jump into list on move up (on win32 it would just circle the item with dotted line/no real select)
489 $filebrowser->SetItemState( 0, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
490 }else{
491 # get position and move down
492 my $currSel = $filebrowser->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
493 my $nextSel = ($currSel - 1);
494 if($nextSel >= 0){ # limit top
495 $filebrowser->SetItemState($currSel, 0, wxLIST_STATE_SELECTED ) if !$event->ShiftDown();
496 $filebrowser->SetItemState(
497 $nextSel,
498 wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED
499 ) unless ($event->ShiftDown() && $filebrowser->GetItemText($nextSel) eq '..');
500 $filebrowser->EnsureVisible($nextSel);
501 }
502 }
503  
504 my $selections = $filebrowser->GetSelections_as_richlist_items();
505 Wrangler::PubSub::publish('selection.changed', scalar(@$selections), $selections );
506 }
507  
508 sub SelectionMoveDown {
509 my $filebrowser = shift;
510 my $event = shift;
511  
512 Wrangler::debug('FileBrowser::SelectionMoveDown: ');
513  
514 if($filebrowser->GetSelectedItemCount() == 0){
515 # jump into list on move down
516 $filebrowser->SetItemState( 0, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
517 }else{
518 # get position and move down
519 my $currSel = $filebrowser->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
520 my $nextSel = $event->ShiftDown() ? ($currSel + $filebrowser->GetSelectedItemCount() ) : ($currSel + 1);
521 if($nextSel <= ($filebrowser->GetItemCount() - 1)){ # limit bottom
522 $filebrowser->SetItemState($currSel, 0, wxLIST_STATE_SELECTED ) if !$event->ShiftDown();
523 $filebrowser->SetItemState(
524 $nextSel,
525 wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED
526 );
527 $filebrowser->EnsureVisible($nextSel);
528 }
529 }
530  
531 my $selections = $filebrowser->GetSelections_as_richlist_items();
532 Wrangler::PubSub::publish('selection.changed', scalar(@$selections), $selections );
533 }
534  
535 sub Columns {
536 my $filebrowser = shift;
537 my $config = $filebrowser->{wrangler}->config();
538 my $columns = $config->{'ui.filebrowser.columns'};
539 $filebrowser->{columns} = $columns;
540  
541 ## now add the columns
542 $filebrowser->{columns_widths_index} = [0];
543 my $accumulated_width;
544 for (0 .. $#{ $columns }){
545 my $align = $columns->[$_]->{text_align} eq 'right' ? wxLIST_FORMAT_RIGHT : wxLIST_FORMAT_LEFT;
546 $filebrowser->InsertColumn( $_, ${ $columns }[$_]->{label}, $align, $columns->[$_]->{width} );
547  
548 ## update our hit->col index, used in GetColumn()
549 $accumulated_width += ${ $columns }[$_]->{width};
550 push(@{ $filebrowser->{columns_widths_index} }, $accumulated_width);
551  
552 ## tell central $wishlist what we are displaying
553 $Wrangler::wishlist->{ $columns->[$_]->{value_from} } = 1;
554 $Wrangler::wishlist->{ 'MIME' } = 1 if $config->{'ui.filebrowser.highlight_media'};
555 }
556 }
557  
558 sub GetColumn {
559 my $filebrowser = shift;
560 my $event = shift;
561  
562 my $click_offset = $event->GetPoint()->x();
563 my $offset_per_scroll_tick = 15; # educated-guess, until we find the Wx method for that, or something like GetLogicalPosition()
564 my $offset = ($filebrowser->GetScrollPos(wxHORIZONTAL) * $offset_per_scroll_tick) + $click_offset;
565 # Wrangler::debug("FileBrowser::GetColumn: $click_offset + ".$filebrowser->GetScrollPos(wxHORIZONTAL)." * $offset_per_scroll_tick");
566 my $hit_col = 0;
567 if(@{ $filebrowser->{columns_widths_index} }){
568 for(0 .. $#{ $filebrowser->{columns_widths_index} }){
569 last if $filebrowser->{columns_widths_index}->[$_] > $offset;
570 $hit_col = $_;
571 }
572 }
573  
574 # Wrangler::debug('FileBrowser::GetColumn: '.$hit_col.' value_from:'.$filebrowser->{columns}->[$hit_col]->{value_from});
575 return wantarray ? ($hit_col,$filebrowser->{columns}->[$hit_col]->{value_from}) : $hit_col;
576 }
577  
578 # expects only a path, as ListCtrl has no idea about hierarchy;
579 # optional args can override default behaviour
580 sub Populate {
581 my $filebrowser = shift;
582 my $richlist = shift || [];
583 my %config = %{ $filebrowser->{wrangler}->config() }; # fewer lookups
584 my %args = (
585 include_updir => $config{'ui.filebrowser.include_updir'} // 1, # /
586 zebra_striping => $config{'ui.filebrowser.zebra_striping'} // 1, # /
587 include_hidden => $config{'ui.filebrowser.include_hidden'} // 0, # /
588 highlight_media => $config{'ui.filebrowser.highlight_media'} // 1, # /
589 highlight_colour_audio => $config{'ui.filebrowser.highlight_colour.audio'} // [220, 220, 240], # /
590 highlight_colour_image => $config{'ui.filebrowser.highlight_colour.image'} // [220, 240, 220], # /
591 highlight_colour_video => $config{'ui.filebrowser.highlight_colour.video'} // [240, 220, 220], # /
592 # colours => $config{'colours'},
593 # colour_labeling => $config{'ui.filebrowser.colour_labeling'} // 1, # /
594 @_
595 );
596  
597 ## set cursor to 'busy', reverts back when local var gets out of scope
598 my $busy = new Wx::BusyCursor;
599  
600 $filebrowser->Show( 0 );
601 $filebrowser->DeleteAllItems();
602 $filebrowser->DeleteAllOurItemData();
603  
604 my $rowCnt = 0;
605 for(@$richlist){
606 next if $_->{'Filesystem::Filename'} eq '.';
607 next if $_->{'Filesystem::Filename'} eq '..' && !$args{include_updir};
608 next if $_->{'Filesystem::Hidden'} && !$args{include_hidden};
609  
610 # map filesystem info to icons (as icons are purely presentational)
611 my $type = $_->{'Filesystem::Type'} eq 'Directory' ? ($_->{'Filesystem::Filename'} eq '..' ? 'go_up' : 'folder') : 'file';
612 if($type eq 'file'){
613 if(my $mediaType = $_->{'MIME::mediaType'}){
614 if($mediaType eq 'image'){
615 $type = 'generic_image';
616 }elsif($mediaType eq 'video'){
617 $type = 'generic_video';
618 }elsif($mediaType eq 'audio'){
619 $type = 'generic_audio';
620 }
621 }
622 }
623  
624 # build row
625 my $itemId;
626 for my $colCnt ( 0 .. $filebrowser->column_count() ){
627 my $column_key = $filebrowser->column_key($colCnt); # less lookups, easier on the eyes
628  
629 # see if the value is already in the richlist, else ask for it (should never happen; unless we fail in telling richlist what to get)
630 my $column_value = defined($_->{$column_key}) ? $_->{$column_key} : ''; # '' was $filebrowser->{wrangler}->{fs}->ask_vfs()
631  
632 # see if there's a renderer for this value-type
633 my $renderer = $filebrowser->{wrangler}->{fs}->renderer($column_key);
634 if($renderer){
635 $column_value = $renderer->($_->{ $column_key });
636 }
637  
638 # use proper insertion method
639 if($colCnt == 0){
640 # InsertItem returns a numeric $itemId
641 $itemId = $filebrowser->InsertImageStringItem( $rowCnt, $column_value, $filebrowser->{images}->{ $type } );
642 }else{
643 $filebrowser->SetItem( $itemId, $colCnt, $column_value );
644 }
645 }
646  
647 # add row data:
648 # as it seems, ListCtrl can hold only numeric data in ItemData,
649 # so we do our own "$itemId (zerobase, numeric) to data" lookup
650 $filebrowser->SetOurItemData($itemId, $_); # we store a ref to our richlist_item
651 # further: might be a bug in Wx, or we're not doing it right, but:
652 # it's not possible to get the right numeric id of a list item via $event->GetItem->GetId, so we set
653 # it as (numeric) data look for string "GetItem()->GetData()" to find code that relies on this workaround
654 $filebrowser->SetItemData($itemId, $itemId);
655  
656 # MIME-mediaType highlighting
657 if($args{highlight_media}){
658 if(my $mediaType = $_->{'MIME::mediaType'}){
659 if($mediaType eq 'image'){
660 $filebrowser->SetItemBackgroundColour($itemId, Wx::Colour->new(@{$args{highlight_colour_image}})); # Image, light green
661 }elsif($mediaType eq 'video'){
662 $filebrowser->SetItemBackgroundColour($itemId, Wx::Colour->new(@{$args{highlight_colour_video}})); # Video, light red
663 }elsif($mediaType eq 'audio'){
664 $filebrowser->SetItemBackgroundColour($itemId, Wx::Colour->new(@{$args{highlight_colour_audio}})); # Audio, light green
665 }
666 }
667 }
668  
669 ## plugin directory_listing per-item manipulations
670 if( my $plugins_ref = Wrangler::PluginManager::plugins('directory_listing') ){
671 for my $plugin (@$plugins_ref){
672 $plugin->directory_listing($filebrowser,$itemId,$_);
673 }
674 }
675  
676 # zebra-striping
677 if($args{zebra_striping} && ($rowCnt % 2)){
678 my @colour;
679 my $colour = $filebrowser->GetItem($itemId)->GetBackgroundColour();
680 @colour = ($colour->Red(), $colour->Green(), $colour->Blue());
681 for(@colour){ $_ -= 7; }
682 $filebrowser->SetItemBackgroundColour($itemId, Wx::Colour->new(@colour));
683 }
684  
685 $rowCnt++;
686 }
687  
688 $filebrowser->Show( 1 );
689 $filebrowser->SetFocus();
690 }
691  
692 sub RePopulate {
693 my $filebrowser = shift;
694  
695 ## remember current selection
696 # How could this be improved? Currently it uses paths as basis - which might change! In many cases, that's why we do a refresh in the first place...
697 my %selection;
698 for( $filebrowser->GetSelections() ){
699 my $richlist_item = $filebrowser->GetOurItemData( $filebrowser->GetItem($_)->GetData() ); # GetOurItemData returns the actual data, no ->GetData needed
700 $selection{ $richlist_item->{'Filesystem::Path'} } = 1;
701 }
702  
703 ## remember ScrollPosition
704 my $scroll_pos_vertical = $filebrowser->GetScrollPos(wxVERTICAL);
705 my $scroll_pos_horizontal = $filebrowser->GetScrollPos(wxHORIZONTAL);
706  
707 ## re-populate/update/refresh listing
708 my $richlist = $filebrowser->{wrangler}->{fs}->richlist( $filebrowser->{current_dir}, Wrangler::wishlist() );
709 $filebrowser->sort_richlist($richlist);
710 $filebrowser->Populate($richlist);
711  
712 ## recreate selection
713 foreach ( 0 .. $filebrowser->GetItemCount - 1 ) {
714 my $richlist_item = $filebrowser->GetOurItemData( $filebrowser->GetItem($_)->GetData() ); # GetOurItemData returns the actual data, no ->GetData needed
715 if( exists($selection{ $richlist_item->{'Filesystem::Path'} }) ){
716 $filebrowser->SetItemState( $_, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
717 }
718 }
719  
720 ## recreate ScrollPos (does not work, at least on nix + Wx 2.8.12, native-ctrl -> feature http://trac.wxwidgets.org/ticket/10267)
721 $filebrowser->SetScrollPos(wxVERTICAL, $scroll_pos_vertical);
722 $filebrowser->SetScrollPos(wxHORIZONTAL, $scroll_pos_horizontal, 'redraw');
723 }
724  
725 sub ChangeDirectory {
726 my ($filebrowser, $path) = @_;
727  
728 Wrangler::PubSub::publish('selection.changed', 0 );
729  
730 (my $richlist,$filebrowser->{current_dir}) = $filebrowser->{wrangler}->{fs}->richlist( $path, Wrangler::wishlist() );
731 Wrangler::debug("FileBrowser::ChangeDirectory: richlist() returned an error listing!") if ref($richlist) eq 'error';
732 $filebrowser->sort_richlist($richlist);
733 $filebrowser->Populate($richlist);
734  
735 my $richprop_dir = $filebrowser->{wrangler}->{fs}->richproperties($filebrowser->{current_dir}, ['Filesystem::Modified']);
736 $filebrowser->{current_dir_mtime} = $richprop_dir->{'Filesystem::Modified'};
737 $filebrowser->{timer}->Start($filebrowser->{wrangler}->config()->{'ui.filebrowser.pull_monitor_timeout'} || 7000, wxTIMER_CONTINUOUS); # schedule simple pull monitoring
738 }
739  
740 sub Mkdir {
741 my $filebrowser = shift;
742  
743 ## find last dir in listing
744 my @selections;
745 my $currId = 0;
746 for(;;){
747 $currId = $filebrowser->GetNextItem($currId, wxLIST_NEXT_ALL, wxLIST_STATE_DONTCARE);
748 if($currId == -1){
749 last;
750 }else{
751 push(@selections, $currId);
752  
753 my $richlist_item = $filebrowser->GetOurItemData( $filebrowser->GetItem($currId)->GetData() );
754 my $path = $richlist_item->{'Filesystem::Path'};
755 if($richlist_item->{'Filesystem::Type'} ne 'Directory'){
756 last;
757 }
758  
759 }
760 }
761  
762 my $lastId = $selections[-1];
763 # Wrangler::debug("Last dir in listing is $lastId");
764  
765 ## insert a placeholder item below dirs
766 my $itemId = $filebrowser->InsertImageStringItem( $lastId,
767 'New folder',
768 $filebrowser->{images}->{ 'folder' }
769 );
770 $filebrowser->SetOurItemData($lastId, { ref_to_ => 'incomplete richlist type data!' });
771 $filebrowser->SetItemData($lastId, $lastId);
772  
773 # make sure the listing is scrolled, so the user can see the new item, and start label edit
774 $filebrowser->EnsureVisible($itemId);
775 $filebrowser->EditLabel($itemId);
776  
777 # this is all we can do here, the directory is actually created in OnEndLabelEdit()
778 $filebrowser->{our_stash} = { mkdir => $itemId };
779 }
780  
781 sub Mknod {
782 my $filebrowser = shift;
783  
784 ## find last dir in listing
785 my @selections;
786 my $currId = 0;
787 for(;;){
788 $currId = $filebrowser->GetNextItem($currId, wxLIST_NEXT_ALL, wxLIST_STATE_DONTCARE);
789 if($currId == -1){
790 last;
791 }else{
792 push(@selections, $currId);
793  
794 my $richlist_item = $filebrowser->GetOurItemData( $filebrowser->GetItem($currId)->GetData() );
795 my $path = $richlist_item->{'Filesystem::Path'};
796 if($richlist_item->{'Filesystem::Type'} ne 'Directory'){
797 last;
798 }
799  
800 }
801 }
802  
803 my $lastId = $selections[-1];
804 # Wrangler::debug("Last dir in listing is $lastId");
805  
806 ## insert a placeholder item below dirs
807 my $itemId = $filebrowser->InsertImageStringItem( $lastId,
808 'New file',
809 $filebrowser->{images}->{ 'file' }
810 );
811 $filebrowser->SetOurItemData($lastId, { ref_to_ => 'richlist type data' });
812 $filebrowser->SetItemData($lastId, $lastId);
813  
814 # make sure the listing is scrolled, so the user can see the new item, and start label edit
815 $filebrowser->EnsureVisible($itemId);
816 $filebrowser->EditLabel($itemId);
817  
818 # this is all we can do here, the directory is actually created in OnEndLabelEdit()
819 $filebrowser->{our_stash} = { mknod => $itemId };
820 }
821  
822 sub Rename {
823 my $filebrowser = shift;
824  
825 my $w = $filebrowser->{wrangler};
826  
827 my @selections = $filebrowser->GetSelections(); # docs: wxPerl note: In wxPerl this method takes no parameters and returns a list of Wx::TreeItemIds.
828 my $selCnt = @selections;
829 Wrangler::debug("FileBrowser: Rename: $selCnt items ");
830  
831 return if $selCnt == 0;
832  
833 for(@selections){
834 push(@{ $filebrowser->{our_stash}->{rename} }, {
835 id => $_,
836 file => $filebrowser->GetItemText($_),
837 richlist_item => $filebrowser->GetOurItemData( $filebrowser->GetItem($_)->GetData() ), # GetOurItemData returns the actual data, no ->GetData needed
838 });
839 }
840  
841 if($selCnt == 1){
842 # the actual rename is done in OnEndEditLabel()
843 # (use the LabelEdit editor to handle the rename)
844 if( $filebrowser->{columns}->[0]->{value_from} eq 'Filesystem::Filename' ){
845 $filebrowser->EditLabel( $selections[0] );
846 # this case handles when the Filename column isn't the first column
847 }else{
848 ## oldpath
849 my $oldpath = ${ $filebrowser->{our_stash}->{rename} }[0]->{richlist_item}->{'Filesystem::Path'};
850 $filebrowser->{our_stash} = undef;
851  
852 my $oldname = $filebrowser->{wrangler}->{fs}->fileparse($oldpath);
853 my $dialog = Wx::TextEntryDialog->new( $filebrowser, "Rename", "Rename", $oldname );
854  
855 unless( $dialog->ShowModal == wxID_CANCEL ){
856 ## newpath
857 my $newpath = $dialog->GetValue();
858 $newpath = decode_utf8($newpath); # decode
859 Encode::_utf8_off($newpath); # then remove the utf8-flag the hard way
860 $newpath = $filebrowser->{wrangler}->{fs}->catfile( $filebrowser->{current_dir}, $newpath);
861  
862 # check if label has been edited
863 return if $oldpath eq $newpath;
864  
865 ## do the actual rename on storage
866 my $ok = $filebrowser->{wrangler}->{fs}->rename($oldpath, $newpath);
867  
868 if($ok){
869 $filebrowser->RePopulate();
870 }else{
871 my $dialog = Wx::MessageDialog->new($filebrowser, "Error renaming \"$oldpath\" to \"$newpath\": $!", "Renaming error", wxOK );
872 $dialog->ShowModal();
873 }
874 }
875  
876 $dialog->Destroy();
877 }
878 }elsif($selCnt > 1){
879 # use a more sophisticated dialogue for multi-renames
880 require Wrangler::Wx::Dialog::MultiRename;
881 my $dialog = Wrangler::Wx::Dialog::MultiRename->new($filebrowser, $filebrowser->{our_stash}->{rename});
882  
883 if($dialog->ShowModal() == wxID_OK){
884 if( $dialog->{pre}->IsModified || $dialog->{ins}->IsModified ){
885 Wrangler::debug("Prepend/append-rename was used ");
886  
887 my $pre = $dialog->{pre}->GetValue();
888 my $ins = $dialog->{ins}->GetValue();
889 $pre = decode_utf8($pre); # decode
890 Encode::_utf8_off($pre); # then remove the utf8-flag the hard way
891 $ins = decode_utf8($ins); # decode
892 Encode::_utf8_off($ins); # then remove the utf8-flag the hard way
893  
894 my @errors;
895 for(@{ $filebrowser->{our_stash}->{rename} }){
896 my $oldpath = $_->{richlist_item}->{'Filesystem::Path'};
897  
898 my ($file, $dirs, $suffix) = $filebrowser->{wrangler}->{fs}->fileparse($oldpath, qr/\.[^.]*/);
899  
900 my $newpath = $filebrowser->{wrangler}->{fs}->catfile( $filebrowser->{current_dir}, $pre.$file.$ins.$suffix);
901 Wrangler::debug("Rename: multi: $oldpath -> $newpath");
902 next if $oldpath eq $newpath;
903  
904 ## do the actual rename
905 my $ok = $filebrowser->{wrangler}->{fs}->rename($oldpath, $newpath);
906 push(@errors, "Error renaming \"$oldpath\" to \"$newpath\": $!\n") unless $ok;
907 }
908 if(@errors){
909 my $dialog = Wx::MessageDialog->new($filebrowser, "@errors", "Renaming error", wxOK );
910 $dialog->ShowModal();
911 }else{
912 $filebrowser->RePopulate();
913 }
914 }elsif( $dialog->{pattern} && $dialog->{pattern}->IsModified ){
915 Wrangler::debug("Pattern-rename was used ");
916  
917 my $multi = $dialog->{multi}->GetValue();
918 $multi = decode_utf8($multi); # decode
919 Encode::_utf8_off($multi); # then remove the utf8-flag the hard way
920 my $oldlen = $dialog->{length};
921 my $newlen = length($multi);
922 Wrangler::debug("MULTI: $multi OLDLEN: $oldlen NEWLEN:$newlen");
923  
924 # todo
925 }
926 }else{
927 Wrangler::debug("Multiple rename CANCELd ");
928 }
929  
930 # clear ourclipboard
931 undef($filebrowser->{our_stash});
932 }
933 }
934  
935 sub ChangeProperty {
936 my $filebrowser = shift;
937 my $metakey = shift;
938  
939 my $w = $filebrowser->{wrangler};
940  
941 my $selections = $filebrowser->GetSelections_as_richlist_items();
942 my $selCnt = @$selections;
943 Wrangler::debug("FileBrowser: ChangeProperty: $selCnt items ");
944  
945 return unless $selCnt;
946  
947 my $dialog = Wx::TextEntryDialog->new($filebrowser, "New value for \"$metakey\":", "Change value of \"$metakey\"", $selections->[0]->{$metakey} );
948 return unless $dialog->ShowModal() == wxID_OK;
949  
950 my $new_value = $dialog->GetValue();
951 $dialog->Destroy();
952  
953 if($selCnt > 2){
954 my $text = "Are you sure you want to change the metadata value on $selCnt items?";
955 my $dialog = Wx::MessageDialog->new($filebrowser, "$text\nThis can't be undone!", $text, wxYES_NO | wxNO_DEFAULT | wxICON_EXCLAMATION );
956 unless($dialog->ShowModal() == wxID_YES){
957 Wrangler::debug("ChangeProperty canceled");
958 return;
959 }
960 }
961  
962 my @errors;
963 for(@$selections){
964 Wrangler::debug("ChangeProperty: set_property($_->{'Filesystem::Path'}, $metakey, $new_value)");
965 my $ok = $filebrowser->{wrangler}->{fs}->set_property($_->{'Filesystem::Path'}, $metakey, $new_value);
966 push(@errors, "Error on set_property($_->{'Filesystem::Path'}, $metakey, $new_value)") unless $ok;
967 }
968  
969 $filebrowser->RePopulate();
970 }
971  
972 sub Delete {
973 my $filebrowser = shift;
974 my $really = shift || 0; # really means we don't move to Trash
975  
976 my $w = $filebrowser->{wrangler};
977  
978 my @selections = $filebrowser->GetSelections(); # docs: wxPerl note: In wxPerl this method takes no parameters and returns a list of Wx::TreeItemIds.
979 my $selCnt = @selections;
980 Wrangler::debug("FileBrowser: Delete(really=".$really."): $selCnt items ");
981 return if $selCnt == 0;
982  
983 if($really && $filebrowser->{wrangler}->config()->{'ui.filebrowser.confirm.delete'}){
984 # confirm dialog
985 my $text = "Are you sure to permanently delete the selected $selCnt item(s)?"; # message grows/stretches the dialog horizontally, in caption/title it doesn't, so we use it twice
986 my $dialog = Wx::MessageDialog->new($filebrowser, "$text\nThis can't be undone!", $text, wxYES_NO | wxNO_DEFAULT | wxICON_EXCLAMATION );
987 unless($dialog->ShowModal() == wxID_YES){
988 Wrangler::debug("Delete canceled");
989 return;
990 }
991 }
992  
993 # create a progress dialog
994 my $pd = Wx::ProgressDialog->new("Deleting...", "Deleting...", $selCnt, $filebrowser, wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_ELAPSED_TIME );
995  
996 # remember above/below (whatever applies) (getNextItem + geometry: _ABOVE/_BELOW does not work )
997 my $prev_id = $selections[0] > 0 ? $selections[0] - 1 : undef;
998 # Wrangler::debug(" prev item above $selections[0] is $prev_id ");
999 my $next_id = $selections[-1] < ($filebrowser->GetItemCount() - 1) ? $selections[-1] + 1 : undef;
1000 # Wrangler::debug(" next item below $selections[-1] (with ".$filebrowser->GetItemCount()." items) is $next_id ");
1001 $prev_id++ if $next_id;
1002  
1003 my $cnt = 1;
1004 my @errors;
1005 for my $currId (reverse @selections){ # http://wiki.wxwidgets.org/WxListCtrl#Deleting_Selected_Rows
1006 my $richlist_item = $filebrowser->GetOurItemData( $filebrowser->GetItem($currId)->GetData() ); # GetOurItemData returns the actual data, no ->GetData needed
1007  
1008 # caveat: in our current implementation, right after a listitem is created via mkdir/mknod, its
1009 # richlist_item data is incomplete until the next (Re)populate - this results in an empty $path here
1010 # and sending an empty string to delete() is probably a bad idea
1011 unless($richlist_item->{'Filesystem::Path'} && $richlist_item->{'Filesystem::Path'} ne ''){
1012 Wrangler::debug("FileBrowser: currId:$currId is an incomplete item! delete skipped!");
1013  
1014 $pd->Update($cnt);
1015 $cnt++;
1016 next;
1017 }
1018  
1019 my $path = $richlist_item->{'Filesystem::Path'};
1020  
1021 ## just to be sure we don't del the 'up-dir'!
1022 ## system's "rm" denies deleting it but rmdir+recursive (=rmtree), which we use here, interprets it as a valid path and deletes it!
1023 if($path =~ /\.\.$/){
1024 Wrangler::debug("FileBrowser: delete ($cnt of $selCnt): currId:$currId, path:$path -- skipped: is 'up-dir'! ");
1025 }else{
1026 if($really){
1027 if( $richlist_item->{'Filesystem::Type'} eq 'Directory' ){
1028 Wrangler::debug("FileBrowser: rmdir('recursive') ($cnt of $selCnt): currId:$currId, path:$path");
1029  
1030 ## delete dir
1031 my $ok = $w->{fs}->rmdir($path,'recursive');
1032 push(@errors, "Error removing dir \"$path\": $!") unless $ok;
1033  
1034 $filebrowser->DeleteItem($currId) if $ok;
1035 }else{
1036 Wrangler::debug("FileBrowser: delete ($cnt of $selCnt): currId:$currId, path:$path");
1037  
1038 ## delete file
1039 my $ok = $w->{fs}->delete($path);
1040 push(@errors, "Error really-deleting file \"$path\": $!") unless $ok;
1041  
1042 $filebrowser->DeleteItem($currId) if $ok;
1043 }
1044 }else{
1045 Wrangler::debug("FileBrowser: trash ($cnt of $selCnt): currId:$currId, path:$path");
1046 my $ok = $w->{fs}->trash($path);
1047 push(@errors, "Error trashing file \"$path\": $!") unless $ok;
1048  
1049 $filebrowser->DeleteItem($currId) if $ok;
1050 }
1051 }
1052  
1053 $pd->Update($cnt);
1054  
1055 $cnt++;
1056 }
1057  
1058 if(@errors){
1059 my $dialog = Wx::MessageDialog->new($filebrowser, "Error deleting ".scalar(@errors) ." item(s):\n".join("\n",@errors), "Delete error", wxOK );
1060 $dialog->ShowModal();
1061 }else{
1062 # $filebrowser->RePopulate();
1063 }
1064  
1065 # select the "next" item after the delete(s)
1066 $filebrowser->SetItemState( $prev_id, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
1067  
1068 # let's cheat here: we modified the listing, removed element(s), and the
1069 # listing should reflect the current state, so don't annoy the user with
1070 # another repopulate; todo: remove this once we change monitoring, or when
1071 # RePopulate() becomes clever enough to update only dirty items
1072 $filebrowser->{current_dir_mtime} = time();
1073  
1074 $filebrowser->SetFocus();
1075 }
1076  
1077 sub OnEndLabelEdit {
1078 my( $filebrowser, $event ) = @_;
1079  
1080 if( $filebrowser->{our_stash}->{mkdir} ){
1081 ## mkdir path
1082 my $path = $event->GetItem->GetText;
1083 $path = decode_utf8($path); # decode
1084 Encode::_utf8_off($path); # then remove the utf8-flag the hard way
1085  
1086 $path = $filebrowser->{wrangler}->{fs}->catfile( $filebrowser->{current_dir}, $path );
1087 my $path_amended;
1088 if( $filebrowser->{wrangler}->{fs}->test('e', $path) ){
1089 for(1..10){
1090 Wrangler::debug("FileBrowser::OnEndLabelEdit: mkdir path $path exists!");
1091 $path .= '_another';
1092 $path_amended = 1;
1093 last if ! $filebrowser->{wrangler}->{fs}->test('e', $path);
1094 }
1095 }
1096  
1097 Wrangler::debug("FileBrowser::OnEndLabelEdit: mkdir: $path");
1098 my $ok = $filebrowser->{wrangler}->{fs}->mkdir($path);
1099  
1100 $filebrowser->{our_stash} = undef;
1101  
1102 if($ok){
1103 $filebrowser->RePopulate() if $path_amended;
1104 }else{
1105 my $dialog = Wx::MessageDialog->new($filebrowser, "Error making directory \"$path\": $!", "Mkdir error", wxOK );
1106 $dialog->ShowModal();
1107 $event->Veto();
1108 # caveat: here, richlist_item data of this newly created item is incomplete! which may lead to errors
1109 # in routines relying on that data - probably, we should do a Repopulate after all item creations
1110 }
1111 }elsif( $filebrowser->{our_stash}->{mknod} ){
1112 ## mknod path
1113 my $path = $event->GetItem->GetText;
1114 $path = decode_utf8($path); # decode
1115 Encode::_utf8_off($path); # then remove the utf8-flag the hard way
1116  
1117 $path = $filebrowser->{wrangler}->{fs}->catfile( $filebrowser->{current_dir}, $path );
1118 my $path_amended;
1119 if( $filebrowser->{wrangler}->{fs}->test('e', $path) ){
1120 for(1..10){
1121 Wrangler::debug("FileBrowser::OnEndLabelEdit: mknod path $path exists!");
1122 $path .= '_another';
1123 $path_amended = 1;
1124 last if ! $filebrowser->{wrangler}->{fs}->test('e', $path);
1125 }
1126 }
1127  
1128 Wrangler::debug("FileBrowser::OnEndLabelEdit: mknod: $path");
1129 my $ok = $filebrowser->{wrangler}->{fs}->mknod($path);
1130  
1131 $filebrowser->{our_stash} = undef;
1132  
1133 if($ok){
1134 $filebrowser->RePopulate() if $path_amended;
1135 }else{
1136 my $dialog = Wx::MessageDialog->new($filebrowser, "Error making node \"$path\": $!", "Mknod error", wxOK );
1137 $dialog->ShowModal();
1138 $event->Veto();
1139 # caveat: here, richlist_item data of this newly created item is incomplete! which may lead to errors
1140 # in routines relying on that data - probably, we should do a Repopulate after all item creations
1141 }
1142 }elsif($filebrowser->{our_stash}->{rename}){
1143 ## oldpath
1144 my $oldpath = $filebrowser->{our_stash}->{rename}->[0]->{richlist_item}->{'Filesystem::Path'};
1145 $filebrowser->{our_stash} = undef;
1146  
1147 ## newpath
1148 my $newpath = $event->GetItem->GetText;
1149 $newpath = decode_utf8($newpath); # decode
1150 Encode::_utf8_off($newpath); # then remove the utf8-flag the hard way
1151 $newpath = $filebrowser->{wrangler}->{fs}->catfile( $filebrowser->{current_dir}, $newpath);
1152  
1153 # check if label has been edited
1154 return if $oldpath eq $newpath;
1155  
1156 ## do the actual rename on storage
1157 my $ok = $filebrowser->{wrangler}->{fs}->rename($oldpath, $newpath);
1158  
1159 if($ok){
1160 # labelEdits already changed the displayed value
1161 # no: $filebrowser->RePopulate(); needed
1162 }else{
1163 my $dialog = Wx::MessageDialog->new($filebrowser, "Error renaming \"$oldpath\" to \"$newpath\": $!", "Renaming error", wxOK );
1164 $dialog->ShowModal();
1165 $event->Veto();
1166 # caveat: here, richlist_item data of this newly created item is incomplete! which may lead to errors
1167 # in routines relying on that data - probably, we should do a Repopulate after all item creations
1168 }
1169  
1170 Wrangler::debug("FileBrowser::OnEndLabelEdit: rename($oldpath, $newpath): $ok $!");
1171  
1172 # let's cheat here: we modified the listing, removed element(s), and the
1173 # listing should reflect the current state, so don't annoy the user with
1174 # another repopulate; todo: remove this once we change monitoring, or when
1175 # RePopulate() becomes clever enough to update only dirty items
1176 $filebrowser->{current_dir_mtime} = time();
1177 }
1178 }
1179  
1180 sub OnActivated {
1181 Wrangler::debug("OnActivated: @_ ");
1182 my( $filebrowser, $event ) = @_;
1183  
1184 # todo: allow multiple files to get activated, but only from one viewer-(file-type)-group
1185 return if $filebrowser->GetSelectedItemCount() > 1;
1186  
1187 my @selections = $filebrowser->GetSelections();
1188 my $richlist_item = $filebrowser->GetOurItemData( $filebrowser->GetItem( shift(@selections) )->GetData() );
1189 my $path = $richlist_item->{'Filesystem::Path'};
1190  
1191 Wrangler::debug("OnActivated: path:$path");
1192  
1193 if( $richlist_item->{'Filesystem::Filename'} eq '..' && $richlist_item->{'Filesystem::Type'} =~ /^Directory$|^Drive$/ ){
1194 my $parent = $filebrowser->{wrangler}->{fs}->parent($richlist_item->{'Filesystem::Path'});
1195  
1196 Wrangler::debug(" change directory: updir/parent: $parent");
1197  
1198 # emit appropriate event
1199 Wrangler::PubSub::publish('dir.activated', $parent);
1200 }elsif( $richlist_item->{'Filesystem::Type'} =~ /^Directory$|^Drive$/ ){
1201 Wrangler::debug(" change directory: $richlist_item->{'Filesystem::Path'}");
1202  
1203 # emit appropriate event
1204 Wrangler::PubSub::publish('dir.activated', $richlist_item->{'Filesystem::Path'});
1205 }else{
1206 # emit appropriate event
1207 Wrangler::PubSub::publish('file.activated', $path, $richlist_item);
1208 }
1209 }
1210  
1211 sub Cut {
1212 my $filebrowser = shift;
1213  
1214 $filebrowser->{our_stash} = { cut => 1 };
1215  
1216 wxTheClipboard->Open();
1217 wxTheClipboard->SetData( $filebrowser->GetSelections_as_FileDataObject() );
1218 wxTheClipboard->Close();
1219 }
1220  
1221 sub Copy {
1222 my $filebrowser = shift;
1223  
1224 delete($filebrowser->{our_stash}->{cut}); # invalidate any remaining 'cut's
1225  
1226 wxTheClipboard->Open();
1227 wxTheClipboard->SetData( $filebrowser->GetSelections_as_FileDataObject() );
1228 wxTheClipboard->Close();
1229 }
1230  
1231 sub Paste {
1232 my $filebrowser = shift;
1233  
1234 wxTheClipboard->Open();
1235 my $fdo = Wx::FileDataObject->new();
1236 my $ok = wxTheClipboard->GetData($fdo);
1237 wxTheClipboard->Close();
1238  
1239 Wrangler::debug("FileBrowser::Paste: ok:$ok");
1240  
1241 # my $focus = Wx::Window::FindFocus();
1242 # if($focus && ref($focus) ne 'Wrangler::Wx::FileBrowser'){
1243 # Wrangler::debug(" FOCUS is not on $focus (caller:".caller().")");
1244 # return;
1245 # }
1246  
1247 unless($ok){
1248 my $dialog = Wx::MessageDialog->new($filebrowser, "The Clipboard doesn't hold files to paste.", "Paste", wxOK );
1249 $dialog->ShowModal();
1250 return;
1251 }
1252  
1253 # create a progress dialog
1254 my $pd = Wx::ProgressDialog->new("File operation in progress...", "File operation...", 1, $filebrowser, wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME );
1255  
1256 my @errors;
1257 for( $fdo->GetFilenames() ){
1258 # it's probably us doing something completely wrong with encodings, BUT: why is this needed? Unless we remove the utf8
1259 # flag here, the concat with {current_dir} results in a wrongly encoded $newpath, which Perl::IO operations choke on;
1260 # the easy explanation would be: Wx messes up our paths while they are in $fdo (or we are not handling it correctly)
1261 my $filepath = decode_utf8($_); # decode
1262 Encode::_utf8_off($filepath); # then remove the utf8-flag the hard way
1263  
1264 my ($name,$path) = $filebrowser->{wrangler}->{fs}->fileparse($filepath);
1265 my $newpath = $filebrowser->{wrangler}->{fs}->catfile($filebrowser->{current_dir}, $name);
1266 if($filebrowser->{our_stash}->{cut}){
1267 # figure out new name: append "_moved"
1268 if( $filebrowser->{wrangler}->{fs}->test('e', $newpath) ){
1269 for(1..10){
1270 Wrangler::debug(" paste: cut/rename/move: newpath $newpath exists!");
1271 $newpath .= '_moved';
1272 last if ! $filebrowser->{wrangler}->{fs}->test('e', $newpath);
1273 }
1274 }
1275  
1276 Wrangler::debug(" paste: cut/rename/move: $filepath => $newpath");
1277 $pd->Pulse("Moving $filepath");
1278  
1279 my $richproperties = $filebrowser->{wrangler}->{fs}->richproperties($filepath, ['Extended Attributes']);
1280  
1281 my $ok = $filebrowser->{wrangler}->{fs}->move($filepath, $newpath);
1282 unless($ok){
1283 Wrangler::debug("Error on paste: cut/rename/move: $! ");
1284 push(@errors, "Error on cut:$filepath -> paste:$newpath: $!");
1285 next;
1286 }
1287  
1288 ## since we use system 'mv' in move(), this is not needed anymore
1289 # Preserving xattr on rename/move is not user-settable, as we compensate for "moves across fs boundaries" here,
1290 # by always using move() instead of rename(). .. All that is mostly opaque to users. A user expects a dwim
1291 # move/mv, and the system command usually *does* preserve xattr
1292  
1293 # if($richproperties){
1294 # Wrangler::debug(" preserving xattribs");
1295 # for my $key (keys %$richproperties ){
1296 # # Wrangler::debug(" - $key");
1297 # $filebrowser->{wrangler}->{fs}->set_property($newpath, $key, $richproperties->{$key}) if $key =~ /^Extended Attributes::/;
1298 # }
1299 # }
1300 }else{
1301 # figure out new name: append "_copy"
1302 if( $filebrowser->{wrangler}->{fs}->test('e', $newpath) ){
1303 for(1..10){
1304 Wrangler::debug(" paste: copy/insert: newpath $newpath exists!");
1305 $newpath .= '_copy';
1306 last if ! $filebrowser->{wrangler}->{fs}->test('e', $newpath);
1307 }
1308 }
1309  
1310 Wrangler::debug(" paste: copy/insert: $filepath => $newpath");
1311 $pd->Pulse("Copying $filepath");
1312  
1313 my $ok = $filebrowser->{wrangler}->{fs}->copy($filepath, $newpath);
1314 unless($ok){
1315 Wrangler::debug("Error on paste: cut/rename/move: $! ");
1316 push(@errors, "Error on copy:$filepath -> paste:$newpath: $!");
1317 next;
1318 }
1319  
1320 if($filebrowser->{wrangler}->config()->{'ui.filebrowser.copy.preserve_xattribs'}){
1321 Wrangler::debug(" preserving xattribs");
1322 my $richproperties = $filebrowser->{wrangler}->{fs}->richproperties($filepath, ['Extended Attributes']);
1323 for my $key (keys %$richproperties ){
1324 # Wrangler::debug(" - $key");
1325 $filebrowser->{wrangler}->{fs}->set_property($newpath, $key, $richproperties->{$key}) if $key =~ /^Extended Attributes::/;
1326 }
1327 }
1328 }
1329 }
1330  
1331 $pd->Destroy();
1332  
1333 if(@errors){
1334 my $dialog = Wx::MessageDialog->new($filebrowser, "Failed to paste ".scalar(@errors) ." item(s):\n".join("\n",@errors), "Paste error", wxOK );
1335 $dialog->ShowModal();
1336 }else{
1337 delete($filebrowser->{our_stash}->{cut});
1338  
1339 $filebrowser->RePopulate();
1340 }
1341 }
1342  
1343 sub PasteSymlinks {
1344 my $filebrowser = shift;
1345  
1346 wxTheClipboard->Open();
1347 my $fdo = Wx::FileDataObject->new();
1348 my $ok = wxTheClipboard->GetData($fdo);
1349 wxTheClipboard->Close();
1350  
1351 Wrangler::debug("FileBrowser::PasteSymlinks: ok:$ok");
1352  
1353 unless($ok){
1354 my $dialog = Wx::MessageDialog->new($filebrowser, "The Clipboard doesn't hold files to paste as symlinks.", "Paste ...as symlinks", wxOK );
1355 $dialog->ShowModal();
1356 return;
1357 }
1358  
1359 for( $fdo->GetFilenames() ){
1360 # it's probably us doing something completely wrong with encodings, BUT: why is this needed? Unless we remove the utf8
1361 # flag here, the concat with {current_dir} results in a wrongly encoded $newpath, which Perl::IO operations choke on;
1362 # the easy explanation would be: Wx messes up our paths while they are in $fdo (or we are not handling it correctly)
1363 my $filepath = decode_utf8($_); # decode
1364 Encode::_utf8_off($filepath); # then remove the utf8-flag the hard way
1365  
1366 my ($name,$path) = $filebrowser->{wrangler}->{fs}->fileparse($filepath);
1367 my $newpath = $filebrowser->{wrangler}->{fs}->catfile($filebrowser->{current_dir}, $name);
1368  
1369 # figure out new name: append "_copy"
1370 if( $filebrowser->{wrangler}->{fs}->test('e', $newpath) ){
1371 for(1..10){
1372 Wrangler::debug(" paste: copy/insert: newpath $newpath exists!");
1373 $newpath .= '_copy';
1374 last if ! $filebrowser->{wrangler}->{fs}->test('e', $newpath);
1375 }
1376 }
1377  
1378 Wrangler::debug(" paste as symlink: $filepath -> $newpath");
1379  
1380 my $ok = $filebrowser->{wrangler}->{fs}->symlink($filepath, $newpath);
1381 Wrangler::debug("Error on paste as symlinks: $! ") unless $ok;
1382 }
1383 delete($filebrowser->{our_stash}->{cut}) if $filebrowser->{our_stash}->{cut};
1384  
1385 $filebrowser->RePopulate();
1386 }
1387  
1388 sub PasteBitmap {
1389 my $filebrowser = shift;
1390  
1391 wxTheClipboard->Open();
1392 my $bdo = Wx::BitmapDataObject->new();
1393 my $ok = wxTheClipboard->GetData($bdo);
1394 wxTheClipboard->Close();
1395  
1396 Wrangler::debug("FileBrowser::PasteBitmap: ok:$ok");
1397  
1398 unless($ok){
1399 my $dialog = Wx::MessageDialog->new($filebrowser, "The Clipboard doesn't hold bitmap data to paste.", "Paste ...as image", wxOK );
1400 $dialog->ShowModal();
1401 return;
1402 }
1403  
1404 my $dialog = Wx::FileDialog->new($filebrowser, "Choose a filename and directory", $filebrowser->{current_dir}, 'clipboard.png', "*.*", wxFD_SAVE|wxFD_OVERWRITE_PROMPT );
1405  
1406 return unless $dialog->ShowModal() == wxID_OK;
1407  
1408 my $path = $dialog->GetPath();
1409 my $type = $path =~ /\.jpg$/ ? wxBITMAP_TYPE_JPEG : wxBITMAP_TYPE_PNG;
1410 $ok = $bdo->GetBitmap()->SaveFile($path, $type);
1411  
1412 unless($ok){
1413 my $error = "PasteBitmap: can't write clipboard's bitmap-data to file: $!";
1414 Wrangler::debug($error);
1415 my $dialog = Wx::MessageDialog->new($filebrowser, $error, "Error on Paste ...as image", wxOK );
1416 $dialog->ShowModal();
1417 return;
1418 }
1419  
1420 $filebrowser->RePopulate();
1421 }
1422  
1423 sub Todo {
1424 my $filebrowser = shift;
1425 my $dialog = Wx::MessageDialog->new($filebrowser, "Not yet implemented", "Not yet implemented", wxOK );
1426 $dialog->ShowModal();
1427 }
1428  
1429 sub OnRightClick {
1430 my $filebrowser = shift;
1431 my $event = shift;
1432  
1433 my $selections = $filebrowser->GetSelections_as_richlist_items();
1434  
1435 my $menu = Wx::Menu->new();
1436  
1437 my ($colId,$col_value_from) = $filebrowser->GetColumn($event);
1438  
1439 if(@$selections){
1440 ## hardcoded file context menu entries
1441 EVT_MENU( $filebrowser, $menu->Append(-1, "View\tENTER", 'Execute/view with viewer'), sub { $filebrowser->OnActivated } );
1442 EVT_MENU( $filebrowser, $menu->Append(-1, "View/open with...", 'Select default viewer/application/command for this mime-type'), sub { Wrangler::PubSub::publish('show.settings', 1, 3); } );
1443 $menu->AppendSeparator();
1444 EVT_MENU( $filebrowser, $menu->Append(-1, "Cut\tCTRL+X", 'Cut' ), sub { $filebrowser->Cut(); } );
1445 EVT_MENU( $filebrowser, $menu->Append(-1, "Copy\tCTRL+C", 'Copy' ), sub { $filebrowser->Copy(); } );
1446 my $itemPaste = Wx::MenuItem->new($menu, -1, "Paste\tCTRL+V", 'Paste');
1447 $menu->Append($itemPaste);
1448 if(0){ # todo: check: we have something in the clipboard AND selection is 1 dir -> "integrate into folder"
1449 $menu->Enable($itemPaste->GetId(),1);
1450 EVT_MENU( $filebrowser, $itemPaste, sub { $filebrowser->Todo(); } );
1451 }else{
1452 $menu->Enable($itemPaste->GetId(),0);
1453 }
1454 $menu->AppendSeparator();
1455 EVT_MENU( $filebrowser, $menu->Append(-1, "Rename\tF2", 'Rename file' ), sub { $filebrowser->Rename(); } );
1456 unless($col_value_from eq 'Filesystem::Filename'){
1457 my $itemChange = Wx::MenuItem->new($menu, -1, "Change '$col_value_from'", "Change '$col_value_from'");
1458 $menu->Append($itemChange);
1459 if( $filebrowser->{wrangler}->{fs}->can_mod($col_value_from) ){
1460 $menu->Enable($itemChange->GetId(),1);
1461 EVT_MENU( $filebrowser, $itemChange, sub { $filebrowser->ChangeProperty($col_value_from); } );
1462 }else{
1463 $menu->Enable($itemChange->GetId(),0);
1464 }
1465 }
1466 EVT_MENU( $filebrowser, $menu->Append(-1, "Create directory", 'Create a directory' ), sub { $filebrowser->Mkdir(); } );
1467 $menu->AppendSeparator();
1468 EVT_MENU( $filebrowser, $menu->Append(-1, "Move to trash\tDEL", 'Move a file to trash' ), sub { $filebrowser->Delete(); } );
1469 EVT_MENU( $filebrowser, $menu->Append(-1, "Delete\tCTRL+DEL", 'Really delete a file or directory' ), sub { $filebrowser->Delete(1); } ) if $filebrowser->{wrangler}->config()->{'ui.filebrowser.offer.delete'};
1470  
1471 ## plugin file context menu entries
1472 if( my $plugins_ref = Wrangler::PluginManager::plugins('file_context_menu') ){
1473 for my $plugin (@$plugins_ref){
1474 if( my $plugin_menu_entries = $plugin->file_context_menu($menu,$selections) ){
1475 $menu->AppendSeparator();
1476 for my $entry ( @$plugin_menu_entries ){
1477 next unless ref($entry) eq 'ARRAY' && ref(${$entry}[0]) eq 'Wx::MenuItem' && ref(${$entry}[1]) eq 'CODE';
1478 EVT_MENU( $filebrowser, $menu->Append( ${$entry}[0] ), ${$entry}[1] );
1479 &{ ${$entry}[2] } if ${$entry}[2];
1480 }
1481 }
1482 }
1483 }
1484  
1485 $menu->AppendSeparator();
1486 EVT_MENU( $filebrowser, $menu->Append(-1, "Properties", 'Show details about current selection' ), sub {
1487 require Wrangler::Wx::Dialog::Properties;
1488 my $selections = $filebrowser->GetSelections_as_richlist_items();
1489 my $dialog = Wrangler::Wx::Dialog::Properties->new($filebrowser,$selections);
1490 $dialog->ShowModal();
1491 $dialog->Destroy();
1492 });
1493 }else{
1494 ## hardcoded folder context menu entries
1495 EVT_MENU( $filebrowser, $menu->Append(-1, "New folder", 'Create a folder' ), sub { $filebrowser->Mkdir(); } );
1496 EVT_MENU( $filebrowser, $menu->Append(-1, "New file", 'Create a file/node' ), sub { $filebrowser->Mknod(); } );
1497 $menu->AppendSeparator();
1498 my $itemPaste = Wx::MenuItem->new($menu, -1, "Paste\tCTRL+V", 'Paste');
1499 my $itemPasteSymlinks = Wx::MenuItem->new($menu, -1, "Paste ...as symlink(s)", 'Paste files on the clipboard as symlinks');
1500 my $itemPasteBitmap = Wx::MenuItem->new($menu, -1, "Paste ...as image", 'Paste clipboard contents as image file');
1501 $menu->Append($itemPaste);
1502 $menu->Append($itemPasteSymlinks);
1503 $menu->Append($itemPasteBitmap);
1504 if(1){ # as it seems, it's safe to assume there's always something in the clipboard
1505 $menu->Enable($itemPaste->GetId(),1);
1506 EVT_MENU( $filebrowser, $itemPaste, sub { $filebrowser->Paste(); } );
1507 $menu->Enable($itemPasteSymlinks->GetId(),1);
1508 EVT_MENU( $filebrowser, $itemPasteSymlinks, sub { $filebrowser->PasteSymlinks(); } );
1509 $menu->Enable($itemPasteBitmap->GetId(),1);
1510 EVT_MENU( $filebrowser, $itemPasteBitmap, sub { $filebrowser->PasteBitmap(); } );
1511 }else{
1512 $menu->Enable($itemPaste->GetId(),0);
1513 }
1514 $menu->AppendSeparator();
1515 EVT_MENU( $filebrowser, $menu->Append(-1, "Zoom in\tCTRL++", 'Zoom in'), sub { Wrangler::PubSub::publish('zoom.in'); } );
1516 EVT_MENU( $filebrowser, $menu->Append(-1, "Zoom standard\tCTRL+0", 'Zoom standard'), sub { Wrangler::PubSub::publish('zoom.standard'); } );
1517 EVT_MENU( $filebrowser, $menu->Append(-1, "Zoom out\tCTRL+-", 'Zoom out'), sub { Wrangler::PubSub::publish('zoom.out'); } );
1518 $menu->AppendSeparator();
1519 EVT_MENU( $filebrowser, $menu->Append(-1, "Export listing as text", ''), sub {
1520 require Wrangler::Wx::Dialog::ListingToText;
1521 Wrangler::Wx::Dialog::ListingToText->new($filebrowser);
1522 });
1523 $menu->AppendSeparator();
1524 EVT_MENU( $filebrowser, $menu->Append(-1, "Settings", 'Settings'), sub { Wrangler::PubSub::publish('show.settings', 1, 0); } );
1525 }
1526  
1527 $filebrowser->PopupMenu( $menu, wxDefaultPosition ); # alt: $event->GetPosition
1528 }
1529  
1530 sub OnChar {
1531 my ($filebrowser, $event) = @_;
1532  
1533 my $keycode = $event->GetKeyCode(); # speedup by less calls
1534  
1535 Wrangler::debug("OnChar: $keycode");
1536  
1537 # more or less ordered by probability
1538 if($keycode == 22 && $event->ControlDown() ){
1539 Wrangler::debug("CTRL+V: Paste/Insert");
1540 $filebrowser->Paste();
1541 }elsif($keycode == 24 && $event->ControlDown() ){
1542 Wrangler::debug("CTRL+X: Cut");
1543 $filebrowser->Cut();
1544 }elsif($keycode == 3 && $event->ControlDown() ){
1545 Wrangler::debug("CTRL+C: Copy");
1546 $filebrowser->Copy();
1547 }elsif($keycode == WXK_ESCAPE){
1548 # if($filebrowser->{in_viewmode}){
1549 # Wrangler::debug("ESC: Filebrowser is viewing: so close Viewer.");
1550 # # $filebrowser->{viewer}->Close();
1551 # # $filebrowser->Show(1);
1552 # }else{
1553 Wrangler::debug("ESC: Deselect all");
1554 $filebrowser->DeselectAll();
1555 # }
1556 }elsif($keycode == WXK_F2){
1557 Wrangler::debug("F2: Rename");
1558  
1559 $filebrowser->Rename();
1560 }elsif($keycode == WXK_DELETE){
1561 Wrangler::debug("Delete");
1562  
1563 $event->ControlDown() ? $filebrowser->Delete('really') : $filebrowser->Delete();
1564 }elsif($keycode == 1 && $event->ControlDown() ){
1565 Wrangler::debug("CTRL+A: Select all");
1566  
1567 $filebrowser->SelectAll();
1568 }elsif($keycode == 9 && $event->ShiftDown() && $event->ControlDown() ){
1569 Wrangler::debug("SHIFT+CTRL+I: Invert selection");
1570  
1571 $filebrowser->InvertSelections();
1572 }elsif($keycode == 18 && $event->ControlDown() ){
1573 Wrangler::debug("CTRL+R: Refresh current view");
1574 $filebrowser->RePopulate();
1575 }elsif($keycode == WXK_BACK){
1576 Wrangler::debug("Backspace: Go one dir up");
1577  
1578 # emit appropriate event
1579 Wrangler::PubSub::publish('dir.activated', $filebrowser->{wrangler}->{fs}->parent($filebrowser->{current_dir}));
1580 }elsif($keycode == WXK_F5){
1581 Wrangler::debug("F5: Refresh current view");
1582 $filebrowser->RePopulate();
1583 }elsif($keycode == 43){
1584 Wrangler::debug("CTRL++: View Zoom-In: ");
1585  
1586 # emit appropriate event
1587 Wrangler::PubSub::publish('zoom.in');
1588 }elsif($keycode == 45){
1589 Wrangler::debug("CTRL+-: View Zoom-Out: ");
1590  
1591 # emit appropriate event
1592 Wrangler::PubSub::publish('zoom.out');
1593 }elsif($keycode == 48){
1594 Wrangler::debug("CTRL+0: View Zoom-Standard: ");
1595  
1596 # emit appropriate event
1597 Wrangler::PubSub::publish('zoom.standard');
1598 }
1599  
1600 $event->Skip(1);
1601 }
1602  
1603 sub Destroy {
1604 my $self = shift;
1605  
1606 Wrangler::PubSub::unsubscribe_owner(__PACKAGE__);
1607  
1608 $self->SUPER::Destroy();
1609 }
1610  
1611 1;