Wrangler/Wx/FileBrowserTreeList.pm untested

filter: Statementstmt 0.0% 0 / 475 Branchbran 0.0% 0 / 148 Conditioncond 0.0% 0 / 32 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 20 totaltotal 0.0% 0 / 703 CC 75 SCAR 44.1
CC
75
Cov
0%
Populate
240.0
OnActivated
110.0
OnChar
110.0
CRAP 82.1
1 package Wrangler::Wx::FileBrowserTreeList;
2  
3 use strict;
4 use warnings;
5  
6 use Wx qw(:everything); # Lazy way to pull in references
7 use base qw(Wx::TreeListCtrl);
8 use Wx::Event qw(:everything); # List required events
9 use HTTP::Date ();
10 use Encode;
11  
12 sub new {
13 my $class = shift;
14 my $parent = shift;
15 my $self = $class->SUPER::new( $parent, -1, wxDefaultPosition, wxDefaultSize,
16 wxTR_HIDE_ROOT|wxTR_HAS_BUTTONS|wxTR_EDIT_LABELS|wxSUNKEN_BORDER
17 | wxTR_HAS_BUTTONS | wxTR_NO_LINES | wxTR_FULL_ROW_HIGHLIGHT | wxTR_MULTIPLE | wxTR_EXTENDED # | wxWANTS_CHARS has no effect
18 );
19  
20 # hook-up access to $wrangler
21 $self->{wrangler} = $parent->{wrangler};
22  
23 # treelist is set-up centrally in Main; link data strctures here
24 $self->SetImageList( ${ $parent->{imagelist} } );
25 $self->{images} = $parent->{images};
26  
27 # hardcoded column-layout for now
28 @{ $self->{columns} } = (
29 { label => 'Name', value_from => 'Filesystem::Filename', text_align => 'left', width => 120 },
30 { label => 'Type', value_from => 'Filesystem::Type', text_align => 'right', width => 100 },
31 { label => 'Modified', value_from => 'Filesystem::Modified', text_align => 'left', width => 140 },
32 { label => 'Size', value_from => 'Filesystem::Size', text_align => 'right', width => 70 },
33 # no icon => values here; as columns do not know about icon presentation
34 );
35  
36 # now add the columns (version switch from WxDemo)
37 my $first = 1;
38 for(reverse @{ $self->{columns} }){
39 my $align = $_->{text_align} eq 'right' ? wxALIGN_RIGHT : wxALIGN_LEFT;
40 if($first){
41 if( $Wx::TreeListCtrl::VERSION > 0.06 ){
42 $self->AddColumn( Wx::TreeListColumnInfo->new($_->{label}, $_->{width}, $align) );
43 }else{
44 $self->AddColumn( $_->{label}, $_->{width}, $align ); # | wxCOL_SORTABLE
45 }
46 undef($first);
47 }else{
48 if( $Wx::TreeListCtrl::VERSION > 0.06 ){
49 $self->InsertColumn(0, Wx::TreeListColumnInfo->new($_->{label}, $_->{width}, $align) );
50 }else{
51 $self->InsertColumn( $_->{label}, $_->{width}, $align );
52 }
53 }
54 # $self->SetColumnEditable(0,1); # col 0, set true
55 # $self->SetSortColumn(0);
56 }
57  
58 ## to mediate between begin/end routines, we use a small internal stash
59 $self->{our_stash} = undef;
60  
61 ## a hidden root node
62 $self->{root} = $self->AddRoot( 'FileBrowser', -1, -1, Wx::TreeItemData->new( 'rootnode' ) ); # using GetRootItem() lead to segmentation faults when root not visible and we entered the tree with arrow up/down...
63  
64 $self->Clear();
65  
66 (my $richlist,$self->{current_dir}) = $self->{wrangler}->{fs}->richlist( $self->{wrangler}->{fs}->cwd() );
67 sort_richlist($richlist);
68 $self->Populate(undef,$richlist);
69  
70 $self->SetFocus();
71 $self->Center();
72  
73 ## Our custom FileBrowser events
74 # To a certain extend, the filebrowser widgets 'know' about what they are
75 # displaying and as such, they emit less generic, more meningful events
76 # Note that we don't use these events here, alhtough we could, for example
77 # for "local action", like what needs to be done when "a directory is activated".
78 # That's because these Events are meant for other widgets, to which we send
79 # a bit of information, but not things like the TreeEvent which is mostly
80 # specific to the local widget and would be send around the app without use.
81 Wrangler::PubSub::subscribe('file.selected', sub { Wrangler::debug("OnFileSelected: @_"); },__PACKAGE__);
82 Wrangler::PubSub::subscribe('file.activated', sub { Wrangler::debug("OnFileActivated: @_"); },__PACKAGE__);
83 Wrangler::PubSub::subscribe('dir.selected', sub { Wrangler::debug("OnDirSelected: @_"); },__PACKAGE__);
84 Wrangler::PubSub::subscribe('dir.activated', sub { Wrangler::debug("OnDirActivated: @_"); },__PACKAGE__);
85 Wrangler::PubSub::subscribe('zoom.in', sub {
86 Wrangler::debug("OnZoomIn: @_");
87  
88 my $size = $self->GetFont()->GetPointSize() + 1;
89 Wrangler::debug(" SetFont: $size");
90 $self->SetFont( Wx::Font->new( $size, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL) );
91 $self->Update();
92 },__PACKAGE__);
93 Wrangler::PubSub::subscribe('zoom.out', sub {
94 Wrangler::debug("OnZoomOut: @_");
95  
96 my $size = $self->GetFont()->GetPointSize() - 1;
97 Wrangler::debug(" SetFont: $size"."");
98 $self->SetFont( Wx::Font->new( $size, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL) );
99 $self->Update();
100 },__PACKAGE__);
101 Wrangler::PubSub::subscribe('zoom.standard', sub {
102 Wrangler::debug("OnZoomStandard: @_");
103  
104 my $size = 11;
105 Wrangler::debug(" SetFont: $size");
106 $self->SetFont( Wx::Font->new( $size, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL) );
107 $self->Update();
108 },__PACKAGE__);
109  
110 ## WxPerl TreeListCtrl (mainly) uses the TreeCtrl EVENT names
111 EVT_TREE_SEL_CHANGING($self, $self, sub { Wrangler::debug("OnSelectionChanging");
112 $_[1]->Veto() if $_[0]->GetItemText( $_[1]->GetItem() ) eq '..';
113 });
114 # Selection is changing. This can be prevented by calling Veto(). Processes a wxEVT_COMMAND_TREE_SEL_CHANGING event type.
115 EVT_TREE_SEL_CHANGED($self, $self, sub {
116 Wrangler::debug("OnSelectionChanged");
117 return unless $_[1]->GetItem(); # click off list bounds
118 });
119 # Process wxEVT_COMMAND_TREELIST_SELECTION_CHANGED event and notifies about the selection change in the control. In the single selection case the item indicated by the event has been selected and previously selected item, if any, was deselected. In multiple selection case, the selection of this item has just changed (it may have been either selected or deselected) but notice that the selection of other items could have changed as well, use wxTreeListCtrl::GetSelections() to retrieve the new selection if necessary.
120 EVT_TREE_ITEM_EXPANDING($self, $self, sub {
121 Wrangler::debug("OnItemExpanding: ");
122  
123 # Note that we don't emit a DIR_ACTIVATION_EVENT here. Even a
124 # TreeCtrl has the notion of a "current dir" and expanding a
125 # sub-directory does not change that "current dir"
126  
127 my $itemId = $_[1]->GetItem();
128 my $richlist_item = $_[0]->GetItemData( $itemId )->GetData();
129  
130 # hack for zebra-striping (TreeListCtrl doesn't count rows)
131 my @zebra_offset;
132 unless($richlist_item->{_cnt} % 2){
133 # Wrangler::debug("user clicked a light row, start with a shaded row");;
134 @zebra_offset = ( 'zebra_offset' => 1 );
135 }
136  
137 my $richlist = $self->{wrangler}->{fs}->richlist($richlist_item->{'Filesystem::Path'});
138 sort_richlist($richlist);
139 Wrangler::debug(" Populate($itemId, $richlist)");
140 $self->Populate($itemId, $richlist, include_updir => 0, @zebra_offset );
141 });
142 # Process wxEVT_COMMAND_TREELIST_ITEM_EXPANDING event notifying about the given branch being expanded. This event is sent before the expansion occurs and can be vetoed to prevent it from happening.
143 EVT_TREE_ITEM_EXPANDED($self, $self, sub { Wrangler::debug("OnItemExpanded: @_"); });
144 # Process wxEVT_COMMAND_TREELIST_ITEM_EXPANDED event notifying about the expansion of the given branch. This event is sent after the expansion occurs and can't be vetoed.
145 EVT_TREE_ITEM_COLLAPSING($self, $self, sub {
146 Wrangler::debug("OnItemCollapsing");
147  
148 my $itemId = $_[1]->GetItem();
149 $_[0]->DeleteChildren($itemId); # free some memory (effect?)
150 $_[0]->AppendItem( $itemId, '...', 0, 1 ); # a placeholder sub entry, to get the "expand" toggle-icon
151 });
152 # The item is being collapsed. This can be prevented by calling Veto(). Processes a wxEVT_COMMAND_TREE_ITEM_COLLAPSING event type.
153 EVT_TREE_ITEM_COLLAPSED($self, $self, sub { Wrangler::debug("OnItemCollapsed"); });
154 # The item has been collapsed. Processes a wxEVT_COMMAND_TREE_ITEM_COLLAPSED event type.
155 # EVT_TREE_ITEM_CHECKED($self, $self, sub { Wrangler::debug("OnItemChecked"); });
156 # Process wxEVT_COMMAND_TREELIST_ITEM_CHECKED event notifying about the user checking or unchecking the item. You can use wxTreeListCtrl::GetCheckedState() to retrieve the new item state and wxTreeListEvent::GetOldCheckedState() to get the previous one.
157 EVT_TREE_ITEM_ACTIVATED($self, $self, sub { OnActivated(@_); });
158 # Process wxEVT_COMMAND_TREELIST_ITEM_ACTIVATED event notifying about the user double clicking the item or activating it from keyboard.
159 EVT_TREE_ITEM_MIDDLE_CLICK($self, $self, sub { Wrangler::debug("OnItemMiddleClick"); });
160 # The user has clicked the item with the middle mouse button. This is only supported by the generic control. Processes a wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK event type.
161 EVT_TREE_ITEM_RIGHT_CLICK($self, $self, sub { Wrangler::debug("OnRightClick"); OnRightClick(@_) });
162 # Process wxEVT_COMMAND_TREELIST_ITEM_CONTEXT_MENU event indicating that the popup menu for the given item should be displayed.
163 EVT_RIGHT_UP($self, sub { Wrangler::debug("OnRightClickUp"); });
164 # The user has right clicked the control with the right mouse button - but not on any item
165 # EVT_TREE_COLUMN_SORTED($self, $self, sub { Wrangler::debug("OnColumnSorted"); });
166 # EVT_TREELIST_COLUMN_SORTED($self, $self, sub { Wrangler::debug("OnColumnSorted"); });
167 # Process wxEVT_COMMAND_TREELIST_COLUMN_SORTED event indicating that the control contents has just been resorted using the specified column. The event doesn't carry the sort direction, use GetSortColumn() method if you need to know it.
168 EVT_LIST_COL_CLICK($self, $self, sub {
169 Wrangler::debug("OnColClick: @_ ");
170  
171 # remember sort col
172 $self->{sort_column} = $_[1]->GetColumn;
173  
174 # toggle sort order
175 $self->{sort_order} = $self->{sort_order} && $self->{sort_order} eq 'DESC' ? 'ASC' : 'DESC';
176  
177 Wrangler::debug("OnColClick: Sort by Col: ". $self->{sort_column} .' = '. $self->column_key($self->{sort_column}) .' sort '. $self->{sort_order});
178  
179 my $richlist = $self->{wrangler}->{fs}->richlist( $self->{wrangler}->{fs}->cwd() );
180 sort_richlist($richlist, sort_on => $self->column_key($self->{sort_column}), sort_order => $self->{sort_order});
181 $self->Populate(undef,$richlist);
182 });
183 #A column (m_col) has been left-clicked. Processes a wxEVT_COMMAND_LIST_COL_CLICK event type.
184 EVT_LIST_COL_RIGHT_CLICK($self, $self, sub { Wrangler::debug("OnColRightClick: @_"); });
185 #A column (m_col) has been right-clicked. Processes a wxEVT_COMMAND_LIST_COL_RIGHT_CLICK event type.
186 EVT_LIST_COL_BEGIN_DRAG($self, $self, sub { Wrangler::debug("OnColBeginDrag: @_"); });
187 #The user started resizing a column - can be vetoed. Processes a wxEVT_COMMAND_LIST_COL_BEGIN_DRAG event type.
188 EVT_LIST_COL_DRAGGING($self, $self, sub { Wrangler::debug("OnColDragging: @_"); });
189 #The divider between columns is being dragged. Processes a wxEVT_COMMAND_LIST_COL_DRAGGING event type.
190 EVT_LIST_COL_END_DRAG($self, $self, sub { Wrangler::debug("OnColEndDrag: @_"); });
191 #A column has been resized by the user. Processes a wxEVT_COMMAND_LIST_COL_END_DRAG event type.
192  
193 EVT_TREE_BEGIN_DRAG($self, $self, sub { Wrangler::debug("OnBeginDrag"); });
194 # Begin dragging with the left mouse button. If you want to enable left-dragging you need to intercept this event and explicitly call wxTreeEvent::Allow(), as it's vetoed by default. Processes a wxEVT_COMMAND_TREE_BEGIN_DRAG event type.
195 EVT_TREE_BEGIN_RDRAG($self, $self, sub { Wrangler::debug("OnBeginRightDrag"); });
196 # Begin dragging with the right mouse button. If you want to enable right-dragging you need to intercept this event and explicitly call wxTreeEvent::Allow(), as it's vetoed by default. Processes a wxEVT_COMMAND_TREE_BEGIN_RDRAG event type.
197 EVT_TREE_END_DRAG($self, $self, sub { Wrangler::debug("OnEndDrag"); });
198 # End dragging with the left or right mouse button. Processes a wxEVT_COMMAND_TREE_END_DRAG event type.
199  
200 EVT_TREE_BEGIN_LABEL_EDIT($self, $self, sub { Wrangler::debug("OnBeginLabelEdit"); });
201 # Begin editing a label. This can be prevented by calling Veto(). Processes a wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT event type.
202 EVT_TREE_END_LABEL_EDIT($self, $self, sub { Wrangler::debug("OnEndLabelEdit"); OnEndLabelEdit(@_); });
203 # Finish editing a label. This can be prevented by calling Veto(). Processes a wxEVT_COMMAND_TREE_END_LABEL_EDIT event type.
204 EVT_TREE_DELETE_ITEM($self, $self, sub { Wrangler::debug("OnDeleteItem"); });
205 # An item was deleted. Processes a wxEVT_COMMAND_TREE_DELETE_ITEM event type. Also called on window desctruction!
206 EVT_TREE_KEY_DOWN($self, $self, sub { Wrangler::debug("OnKeyDown"); OnChar(@_); } );
207 # A key has been pressed. Processes a wxEVT_COMMAND_TREE_KEY_DOWN event type.
208 # overrides default key-navigation!
209 # EVT_TREE_ITEM_GETTOOLTIP($self, $self, sub { Wrangler::debug("OnGetTooltip"); });
210 # The opportunity to set the item tooltip is being given to the application (call wxTreeEvent::SetToolTip). Windows only. Processes a wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP event type.
211 EVT_TREE_ITEM_MENU($self, $self, sub { Wrangler::debug("OnItemContextMenu"); OnRightClick(@_); });
212 # The context menu for the selected item has been requested, either by a right click or by using the menu key. Processes a wxEVT_COMMAND_TREE_ITEM_MENU event type.
213  
214 # EVT_TREE_GET_INFO(id, func);
215 # Request information from the application. Processes a wxEVT_COMMAND_TREE_GET_INFO event type.
216 # EVT_TREE_SET_INFO(id, func);
217 # Information is being supplied. Processes a wxEVT_COMMAND_TREE_SET_INFO event type.
218  
219 # EVT_TREE_STATE_IMAGE_CLICK(id, func):
220 # The state image has been clicked. Windows only. Processes a wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK event type.#
221  
222 # has no effect, even with style == wxWANTS_CHARS
223 # EVT_CHAR( $self, \&OnChar );
224 EVT_PAINT($self, sub {
225 # Wrangler::debug("OnPaint: @_");
226 $self->OptimiseColumns();
227 });
228 EVT_SIZE($self, sub {
229 Wrangler::debug("OnSize: @_");
230 $self->OptimiseColumns(1);
231 $_[1]->Skip(1);
232 });
233  
234 return $self;
235 }
236  
237 sub Clear {
238 my ($filebrowser) = @_;
239  
240 $filebrowser->DeleteChildren( $filebrowser->{root} );
241 }
242  
243 sub FinaliseLayout {
244 my $filebrowser = shift;
245 $filebrowser->OptimiseColumns();
246 }
247  
248 sub OptimiseColumns {
249 my $filebrowser = shift;
250 my $force = shift;
251 return if !$force && $filebrowser->{columns_optimised};
252  
253 ## optimise column width
254 # my $width = $filebrowser->GetViewRect()->width; # is completely off
255 my $width = $filebrowser->GetClientSize()->width;
256 my $width_half = int( ($width + 50) / 2); # +50 to compensate for $width being too small
257 $filebrowser->SetColumnWidth (0, $width_half );
258  
259 my $colCnt = $filebrowser->GetColumnCount();
260 Wrangler::debug("OptimiseColumns: width:$width; width_half:$width_half; colCnt:$colCnt");
261 for(1 .. $colCnt){
262 $filebrowser->SetColumnWidth($_, int( $width_half / $colCnt ) );
263 }
264 }
265  
266  
267 ## who should know about sorting, Wx, the vfs, or wrangler? Wx is only presentation,
268 ## so 'No'; the vfs is like fuse or the raw fs: no idea of sorting; and as expected,
269 ## it's wrangler who does the sorting, so this is a helper offered by wrangler that
270 ## can handle richlists, and does sorting like people expect it in a file-listing
271 my $regex_numeric = qr/^\d+$/;
272 sub sort_richlist {
273 my $richlist = shift;
274 my $args = {
275 sort_on => 'Filesystem::Filename',
276 sort_order => 'ASC',
277 @_
278 };
279  
280 my $sort_on = $args->{sort_on};
281  
282 ## separate types ; this is how we currently implement the two-level
283 ## sorting of 'on types' first, then 'by name'
284 ## we treat updir separately, so it's always first, sorting is still not perfect, as dotfiles
285 ## come after files starting with ! for example, should probably be the other way 'round
286 my (@devices,@updir,@dirs,@files);
287 my $data_type = 'numeric';
288 for(@$richlist){
289 if($_->{'Filesystem::Type'} eq 'Directory'){
290 if(!@updir && $_->{'Filesystem::Filename'} eq '..'){
291 push(@updir, $_);
292 }else{
293 push(@dirs, $_);
294 }
295 }elsif($_->{'Filesystem::Type'} eq 'File'){
296 push(@files, $_);
297 }else{
298 push(@devices, $_);
299 }
300 $data_type = 'alphanumeric' unless $_->{ $sort_on } =~ $regex_numeric;
301 }
302 @$richlist = ();
303  
304 Wrangler::debug("sort_richlist: sort_on:$args->{sort_on}, sort_order:$args->{sort_order}, data_type:$data_type");
305  
306 if($data_type eq 'numeric'){
307 # numeric
308 if($args->{sort_order} eq 'DESC'){
309 @dirs = sort { $b->{ $sort_on } <=> $a->{ $sort_on } } @dirs;
310 push(@dirs,@updir);
311 @files = sort { $b->{ $sort_on } <=> $a->{ $sort_on } } @files;
312 }else{
313 @dirs = sort { $a->{ $sort_on } <=> $b->{ $sort_on } } @dirs;
314 unshift(@dirs,@updir);
315 @files = sort { $a->{ $sort_on } <=> $b->{ $sort_on } } @files;
316 }
317 }else{
318 # alphanumeric
319 if($args->{sort_order} eq 'DESC'){
320 @dirs = sort { lc($b->{ $sort_on }) cmp lc($a->{ $sort_on }) } @dirs;
321 push(@dirs,@updir);
322 @files = sort { lc($b->{ $sort_on }) cmp lc($a->{ $sort_on }) } @files;
323 }else{
324 @dirs = sort { lc($a->{ $sort_on }) cmp lc($b->{ $sort_on }) } @dirs;
325 unshift(@dirs,@updir);
326 @files = sort { lc($a->{ $sort_on }) cmp lc($b->{ $sort_on }) } @files;
327 }
328 }
329  
330 @$richlist = (@devices,@dirs,@files);
331  
332 return $richlist;
333 }
334  
335 sub column_count {
336 return $#{ $_[0]->{columns} };
337 }
338 sub column_key {
339 return ${ $_[0]->{columns} }[ $_[1] ]->{value_from};
340 }
341  
342 sub SelectAll {
343 my $filebrowser = shift;
344  
345 # no luck GetFirst/LastChild returns 0 instead of an ItemId obj
346  
347 my $cookie;
348 # my $itemId = $filebrowser->GetFirstChild($filebrowser->{root});
349 my $itemId = $filebrowser->{root};
350 Wrangler::debug("SelectAll: $filebrowser->{root} $itemId");
351 my $cnt;
352 for(;;){
353 $itemId = $filebrowser->GetNextChild($itemId);
354 Wrangler::debug(" - $itemId");
355 $filebrowser->SelectItem($itemId);
356 $cnt++;
357 last unless $itemId;
358 }
359  
360 # my $cookie;
361 # my $itemId = $filebrowser->GetFirstChild($filebrowser->{root});
362 # Wrangler::debug(" $itemId");
363 # for(;;){
364 # $itemId = $filebrowser->GetNextItem($itemId,$cookie);
365 # Wrangler::debug(" 1 ");
366 # }
367  
368 # foreach ( 0 .. $filebrowser->GetItemCount - 1 ) {
369 # if($_ == 0){
370 # next if $filebrowser->GetItemText($_) eq '..';
371 # }
372 # $filebrowser->SetItemState( $_, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
373 # }
374  
375 $filebrowser->{wrangler}->publish('selection.changed', $cnt) if $cnt;
376 }
377  
378 sub DeselectAll {
379 my $filebrowser = shift;
380  
381 $filebrowser->UnselectAll();
382  
383 $filebrowser->{wrangler}->publish('selection.changed', 0);
384 }
385  
386 sub InvertSelections {
387 my $filebrowser = shift;
388  
389 my $cnt;
390 foreach ( 0 .. $filebrowser->GetItemCount - 1 ) {
391 if($_ == 0){
392 next if $filebrowser->GetItemText($_) eq '..';
393 }
394  
395 my $state = $filebrowser->GetItemState( $_, wxLIST_STATE_SELECTED );
396  
397 if($state == wxLIST_STATE_SELECTED){
398 $filebrowser->SetItemState( $_, 0, wxLIST_STATE_SELECTED );
399 $cnt++;
400 }else{
401 $filebrowser->SetItemState( $_, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
402 }
403 }
404  
405 $filebrowser->{wrangler}->publish('selection.changed', $cnt) if $cnt;
406 }
407  
408 # expects a parent tree-element and a path; optional args can override default behaviour
409 sub Populate {
410 my $filebrowser = shift;
411 my $element = shift || $filebrowser->{root};
412 my $richlist = shift || [];
413 my %args = (
414 include_updir => $filebrowser->{wrangler}->config()->{'ui.filebrowser.include_updir'} // 1, # /
415 zebra_striping => $filebrowser->{wrangler}->config()->{'ui.filebrowser.zebra_striping'} // 1, # /
416 include_hidden => $filebrowser->{wrangler}->config()->{'ui.filebrowser.include_hidden'} // 0, # /
417 zebra_offset => 0, # TreeCtrl specific
418 @_
419 );
420  
421 ## set cursor to 'busy', reverts back when local var gets out of scope
422 my $busy = new Wx::BusyCursor;
423  
424 $filebrowser->Show( 0 );
425 $filebrowser->DeleteChildren($element); # mostly for subdirs, which we populate with "..." to trigger the "expandable" icon
426  
427 my $rowCnt = 0;
428 for(@$richlist){
429 next if $_->{'Filesystem::Filename'} eq '.';
430 next if $_->{'Filesystem::Filename'} eq '..' && !$args{include_updir};
431 next if $_->{'Filesystem::Hidden'} && !$args{include_hidden};
432  
433 # build row
434 my $item;
435 for my $colCnt ( 0 .. $filebrowser->column_count() ){
436 my $column_key = $filebrowser->column_key($colCnt); # less lookups, easier on the eyes
437  
438 # 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)
439 my $column_value = defined($_->{$column_key}) ? $_->{$column_key} : $filebrowser->{wrangler}->{fs}->ask_vfs();
440  
441 # see if there's a renderer for this value-type
442 my $renderer = $filebrowser->{wrangler}->{fs}->renderer($column_key);
443 if($renderer){
444 $column_value = $renderer->($_->{ $column_key });
445 }
446  
447 # use proper insertion method
448 if($colCnt == 0){
449 # returns $item = Wx::TreeItemId obj
450 $item = $filebrowser->AppendItem( $element,
451 $column_value,
452 0, 1, Wx::TreeItemData->new( $_ ) # we store a ref to the richlist_item
453 );
454 }else{
455 $filebrowser->SetItemColumnText( $item, $colCnt, $column_value );
456 }
457 }
458  
459 if( $_->{'Filesystem::Type'} eq 'Directory' ){
460 if($_->{'Filesystem::Filename'} eq '..'){
461 $filebrowser->SetItemImage( $item, 0, $filebrowser->{images}->{go_up});
462 }else{
463 $filebrowser->SetItemImage( $item, 0, $filebrowser->{images}->{folder});
464  
465 # a placeholder sub entry, to get the "expand" toggle-icon
466 my $subtree = $filebrowser->AppendItem( $item, '...', 0, 1 );
467 }
468 }else{
469 $filebrowser->SetItemImage( $item, 0, $filebrowser->{images}->{file});
470 }
471  
472 # MIME-mediaType highlighting
473 my ($col_hi,$col_low) = (235,220);
474 if(my $mediaType = $_->{'MIME::mediaType'}){
475 if($mediaType eq 'video'){
476 $filebrowser->SetItemBackgroundColour($item, Wx::Colour->new($col_hi, $col_low, $col_low)); # Video, light red: 235, 220, 220
477 }elsif($mediaType eq 'image'){
478 $filebrowser->SetItemBackgroundColour($item, Wx::Colour->new($col_low, $col_hi, $col_low)); # Image, light green: 220, 235, 220
479 }elsif($mediaType eq 'audio'){
480 $filebrowser->SetItemBackgroundColour($item, Wx::Colour->new($col_low, $col_low, $col_hi)); # Audio, light green: 220, 220, 235
481 # }elsif($mediaType eq 'child'){ # unused
482 # $filebrowser->SetItemBackgroundColour($item, Wx::Colour->new(220,220,220));
483 }
484 }
485  
486 # zebra-striping
487 if($args{zebra_striping} && (($rowCnt + $args{zebra_offset}) % 2)){
488 my @colour;
489 if('intelligent'){
490 my $colour = $filebrowser->GetItemBackgroundColour($item);
491 @colour = ($colour->Red(), $colour->Green(), $colour->Blue());
492 for(@colour){ $_ -= 7; }
493 }else{ # 'fast'
494 @colour = (248,248,248);
495 }
496 $filebrowser->SetItemBackgroundColour($item, Wx::Colour->new(@colour));
497 }
498  
499 $rowCnt++;
500 }
501  
502 $filebrowser->Show( 1 );
503 }
504  
505  
506 sub Mkdir {
507 my $filebrowser = shift;
508  
509 ## find last dir in listing
510 my @selections;
511 my $currId = 0;
512 for(;;){
513 $currId = $filebrowser->GetNextSibling($currId);
514 if($currId == -1){
515 last;
516 }else{
517 push(@selections, $currId);
518 Wrangler::debug(" push $currId ");
519  
520 my $richlist_item = $filebrowser->GetOurItemData( $filebrowser->GetItem($currId)->GetData() );
521 my $path = $richlist_item->{'Filesystem::Path'};
522 if($richlist_item->{'Filesystem::Type'} ne 'Directory'){
523 # pop(@selections);
524 last;
525 }
526  
527 }
528 }
529  
530 my $lastId = $selections[-1];
531 # Wrangler::debug("Last dir in listing is $lastId");
532  
533 ## insert a placeholder item below dirs
534 my $itemId = $filebrowser->InsertImageStringItem( $lastId,
535 'New directory',
536 $filebrowser->{images}->{ 'folder' }
537 );
538 $filebrowser->SetOurItemData($lastId, { ref_to_ => 'richlist type data' });
539 $filebrowser->SetItemData($lastId, $lastId);
540  
541 # make sure the listing is scrolled, so the user can see the new item, and start label edit
542 $filebrowser->EnsureVisible($itemId);
543 $filebrowser->EditLabel($itemId);
544  
545 # this is all we can do here, the directory is actually created in OnEndLabelEdit()
546 $filebrowser->{our_stash} = { mkdir => $itemId };
547 }
548  
549 sub Rename {
550 my $filebrowser = shift;
551  
552 my $w = $filebrowser->{wrangler};
553  
554 my @selections = $filebrowser->GetSelections(); # docs: wxPerl note: In wxPerl this method takes no parameters and returns a list of Wx::TreeItemIds.
555 my $selCnt = @selections;
556 Wrangler::debug("FileBrowser: Rename: $selCnt items ");
557  
558 for(@selections){
559 push(@{ $filebrowser->{our_stash}->{rename} }, {
560 id => $_,
561 file => $filebrowser->GetItemText($_),
562 });
563 }
564  
565 if($selCnt == 0){
566 return;
567 }elsif($selCnt == 1){
568 # the actual rename is done in OnEndEditLabel()
569 # (use the LabelEdit editor to handle the rename)
570 $filebrowser->EditLabel( $selections[0] );
571 }elsif($selCnt > 1){
572 # use a more sophisticated dialogue for multi-renames
573 require Wrangler::Dialog::MultiRename;
574 my $dialog = Wrangler::Dialog::MultiRename->new($filebrowser->{our_stash}->{rename});
575  
576 if($dialog->ShowModal() == wxID_OK){
577 if( $dialog->{pre}->IsModified || $dialog->{ins}->IsModified ){
578 Wrangler::debug("Prepend/append-rename was used ");
579  
580 my $pre = $dialog->{pre}->GetValue();
581 my $ins = $dialog->{ins}->GetValue();
582  
583 foreach my $item (@{ $filebrowser->{ourclipboard} }){
584 my $oldpath = File::Spec->catfile( $filebrowser->{current_dir}, $item->{file});
585  
586 my ($file, $dirs, $suffix) = File::Basename::fileparse($item->{file}, qr/\.[^.]*/);
587  
588 my $newpath = File::Spec->catfile( $filebrowser->{current_dir}, $pre.$file.$ins.$suffix);
589  
590 next if $oldpath eq $newpath; # prevent that the update-internal-tree gets corrupted, and of course an unnecessary fs IO
591 # todo: check this via the OnEditLabel dirty? function
592  
593 ## do the actual rename
594 $filebrowser->{wrangler}->{fs}->rename($oldpath, $newpath);
595  
596 ## update the internal metadata tree
597 # $self->{tree}->{$newpath} = $self->{tree}->{$oldpath};
598 # delete($self->{tree}->{$oldpath});
599  
600 ## update GUI
601 Wrangler::debug("Wrangler::FileBrowser::rename(multi): rename($oldpath, $newpath) ");
602 $filebrowser->SetItemText($item->{id}, $pre.$file.$ins.$suffix);
603 }
604 }elsif( $dialog->{multi}->IsModified ){
605 Wrangler::debug("Pattern-rename was used ");
606  
607 my $multi = $dialog->{multi}->GetValue();
608 $multi = decode_utf8($multi); # decode
609 Encode::_utf8_off($multi); # then remove the utf8-flag the hard way
610 my $oldlen = $dialog->{length};
611 my $newlen = length($multi);
612 Wrangler::debug("MULTI: $multi OLDLEN: $oldlen NEWLEN:$newlen");
613 }
614 }else{
615 Wrangler::debug("Multiple rename CANCELd ");
616 }
617  
618 # clear ourclipboard
619 undef($filebrowser->{our_stash});
620  
621 # Fire the rename via the Event which are triggered by EditLabel OnBEginEdit / OnEndEdit
622 # $filebrowser->EditLabel($selId);
623 }
624 }
625  
626  
627 sub OurDelete { # treelistctrl has a Delete() as well!
628 my $filebrowser = shift;
629  
630 my $w = $filebrowser->{wrangler};
631  
632 my @selections = $filebrowser->GetSelections(); # docs: wxPerl note: In wxPerl this method takes no parameters and returns a list of Wx::TreeItemIds.
633 my $selCnt = @selections;
634 return if $selCnt == 0;
635 Wrangler::debug("FileBrowser: delete: $selCnt items ");
636  
637 # create a progress dialog
638 my $pd = Wx::ProgressDialog->new("Deleting...", "Deleting...", $selCnt, $filebrowser, wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME );
639  
640 my $cnt=1;
641 for my $currId (@selections){
642 my $richlist_item = $filebrowser->GetItemData( $currId )->GetData();
643 my $path = $richlist_item->{'Filesystem::Path'};
644  
645 ## just to be sure we don't del the 'up-dir'!
646 ## system's "rm" denies deleting it but rmtree, which we use here, inteprets it as a valid path and deletes it!
647 if($path =~ /\.\.$/){
648 Wrangler::debug("FileBrowser: skipped delete of the 'up-dir'! ");
649 $pd->Update($_);
650 next;
651 }
652  
653 if( $richlist_item->{'Filesystem::Type'} eq 'Directory' ){
654 Wrangler::debug("FileBrowser: delete ($cnt of $selCnt): currId:$currId, path:$path");
655  
656 ## delete dir
657 # $w->{fs}->rmdir($path);
658 }else{
659 Wrangler::debug("FileBrowser: delete ($cnt of $selCnt): currId:$currId, path:$path");
660  
661 ## delete file
662 # $w->{fs}->delete($path);
663 }
664  
665 $filebrowser->DeleteChildren($currId);
666 $filebrowser->Delete($currId);
667  
668 $pd->Update($cnt);
669 $cnt++;
670 last if $cnt > $selCnt;
671 }
672  
673 # select the 'next' item after the delete(s)
674 # if($_ == $selCnt){
675 # my $next_id = $filebrowser->GetNextItem($currId, wxLIST_NEXT_ALL);
676 # $filebrowser->SetItemState( $next_id, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
677 # }
678  
679 $filebrowser->SetFocus();
680 }
681  
682  
683 sub OnEndLabelEdit {
684 my( $filebrowser, $event ) = @_;
685  
686 if( $filebrowser->{our_stash}->{mkdir} ){
687 ## mkdir path
688 my $path = $filebrowser->GetItemText( $event->GetItem );
689 $path = decode_utf8($path); # decode
690 Encode::_utf8_off($path); # then remove the utf8-flag the hard way
691  
692 # $path = File::Spec->catfile( $filebrowser->{current_dir}, $path );
693 Wrangler::debug(" mkdir: $path");
694 # $filebrowser->{wrangler}->{fs}->mkdir($path);
695  
696 $filebrowser->{our_stash} = undef;
697 }else{
698 ## oldpath
699 my $oldpath = ${ $filebrowser->{our_stash}->{rename} }[0]->{file};
700 $filebrowser->{our_stash} = undef;
701  
702 ## newpath
703 my $newpath = $filebrowser->GetItemText( $event->GetItem() );
704 $newpath = decode_utf8($newpath); # decode
705 Encode::_utf8_off($newpath); # then remove the utf8-flag the hard way
706 # $newpath = File::Spec->catfile( $filebrowser->{current_dir}, $newpath);
707  
708 ## we've got a BUG here: GetItemText returns the string the item had *before* the edit,
709 ## but we're in OnEndLabelEdit here...
710  
711 # check if label has been edited
712 return if $oldpath eq $newpath;
713  
714 # ## do the actual rename on storage
715 # $self->{wrangler}->{fs}->rename($oldpath, $newpath);
716  
717 Wrangler::debug(" rename($oldpath, $newpath)");
718 }
719 }
720  
721  
722 sub OnActivated {
723 Wrangler::debug("OnActivated: @_ ");
724 my( $filebrowser, $event ) = @_;
725  
726 # todo: allow multiple files to get activated, but only from one viewer-(file-type)-group
727 return if $filebrowser->GetSelectedItemCount() > 1;
728  
729 my @selections = $filebrowser->GetSelections();
730 my $richlist_item = $filebrowser->GetOurItemData( $filebrowser->GetItem( shift(@selections) )->GetData() );
731 my $path = $richlist_item->{'Filesystem::Path'};
732  
733 Wrangler::debug("OnActivated: path:$path");
734  
735 if( $richlist_item->{'Filesystem::Type'} =~ /^Directory$|^Drive$/ ){
736 (my $richlist,$path) = $filebrowser->{wrangler}->{fs}->richlist( $richlist_item->{'Filesystem::Path'} );
737  
738 Wrangler::debug(" change directory: $path");
739  
740 # emit appropriate event
741 $filebrowser->{wrangler}->publish('dir.activated', $path);
742  
743 sort_richlist($richlist);
744 $filebrowser->Populate($richlist);
745 $filebrowser->{current_dir} = $path;
746  
747 $filebrowser->{wrangler}->publish('directory.focus', $path);
748 }else{
749 # emit appropriate event
750 $filebrowser->{wrangler}->publish('file.activated',$path);
751  
752 Wrangler::debug(" is a file");
753  
754 # my $type = Wrangler::Scan::type_from_ext($itemText);
755 my $type = 'image';
756 if($type eq 'video'){
757 if('external video viewer'){
758 my $pid = ForkAndExec('/usr/bin/avplay', $richlist_item->{'Filesystem::Path'} );
759 # $self->{statusbar}->SetStatusText("Launched external video-viewer with pid $pid",2)
760 }else{
761 # $filebrowser->{viewer} = Wrangler::VideoViewer->new( $self ) if !$filebrowser->{viewer};
762  
763 # $self->Show(0);
764 # $filebrowser->{viewer}->Show(1);
765  
766 # $filebrowser->{viewer}->Load(
767 # File::Spec->catfile( $filebrowser->{current_dir}, $itemText), $itemText
768 # );
769 }
770 }elsif($type eq 'image'){
771 if('external image viewer'){
772 # do local action
773 Wrangler::debug(" defined OnFileActivated action: ForkAndExec('viewnior', $richlist_item->{'Filesystem::Path'})");
774 # maybe we should let this event propagate up to Wrangler, to shoot the viewing app...
775 my $pid = ForkAndExec('/usr/local/bin/viewnior', $richlist_item->{'Filesystem::Path'} );
776 ## my $pid = ForkAndExec('/usr/bin/eog', $richlist_item->{'Filesystem::Path'} );
777 # $self->{statusbar}->SetStatusText("Launched external image-viewer with pid $pid",2)
778 }else{
779 # $filebrowser->{viewer} = Wrangler::ImageViewer->new( $filebrowser ) if !$filebrowser->{viewer};
780 # # $self->Show(0);
781 # ## $filebrowser->{viewer}->SetFocus();
782 # ## Wrangler::debug("=== Find Focus ". Wx::Window::FindFocus() );
783  
784 # $filebrowser->{viewer}->Load(
785 # File::Spec->catfile( $filebrowser->{current_dir}, $itemText), $itemText
786 # );
787 }
788 }elsif($type eq 'audio'){
789 if('external audio viewer'){
790 my $pid = ForkAndExec('/usr/bin/smplayer %s', $richlist_item->{'Filesystem::Path'} );
791 # $self->{statusbar}->SetStatusText("Launched external audio-viewer with pid $pid",2)
792 }else{
793 # $filebrowser->{viewer} = Wrangler::SoundViewer->new( $self ) if !$filebrowser->{viewer};
794  
795 # $self->Show(0);
796 # $filebrowser->{viewer}->Show(1);
797  
798 # $filebrowser->{viewer}->Load(
799 # File::Spec->catfile( $filebrowser->{current_dir}, $itemText), $itemText
800 # );
801 }
802 }elsif($type eq 'playlist'){
803 Wrangler::Dialog::PlaylistEditor->new($path);
804 }else{
805 print 'Is File: we can\'t handle. returning.';
806 return;
807 }
808 }
809 }
810  
811  
812 sub OnRightClick {
813 my $filebrowser = shift;
814 my $event = shift;
815 my $w = $filebrowser->{wrangler};
816  
817 my $menu = Wx::Menu->new();
818  
819 ## hardcoded entries
820 EVT_MENU( $filebrowser, $menu->Append(-1, "View\tENTER", 'Execute/view with viewer'), sub { $filebrowser->OnActivated } );
821 $menu->AppendSeparator();
822 EVT_MENU( $filebrowser, $menu->Append(-1, "Create directory", 'Create a directory' ), sub { $filebrowser->Mkdir(); } );
823 EVT_MENU( $filebrowser, $menu->Append(-1, "Delete\tDEL", 'Delete a file or directory' ), sub { $filebrowser->OurDelete(); } ); # treelistctrl has a Delete() as well!
824 EVT_MENU( $filebrowser, $menu->Append(-1, "Rename\tF2", 'Rename file' ), sub { $filebrowser->Rename(); } );
825  
826 ## plugin entries
827 if( my $plugins_ref = $w->{plugin_manager}->plugins('context_menu') ){
828 $menu->AppendSeparator();
829  
830 for my $plugin (@{ $plugins_ref }){
831 for my $entry ( @{ $plugin->menu_entries } ){
832 EVT_MENU( $filebrowser, $menu->Append(-1, ${$entry}[0], ${$entry}[1] ), ${$entry}[2] );
833 }
834 }
835 }
836  
837 $filebrowser->PopupMenu( $menu, wxDefaultPosition ); # alt: $event->GetPosition
838 }
839  
840  
841 sub OnChar {
842 my( $filebrowser, $event ) = @_;
843  
844 my $keycode = $event->GetKeyCode(); # speedup by less calls
845  
846 Wrangler::debug("OnChar: $keycode");
847  
848 if($keycode == 9){
849 Wrangler::debug("SHIFT+CTRL+I: Invert selection");
850  
851 $filebrowser->InvertSelections();
852 }elsif($keycode == 1){
853 Wrangler::debug("CTRL+A: Select all");
854  
855 $filebrowser->SelectAll();
856 }elsif($keycode == 43){
857 Wrangler::debug("CTRL++: View Zoom-In: ");
858  
859 # emit appropriate event
860 $filebrowser->{wrangler}->publish('zoom.in');
861 }elsif($keycode == 45){
862 Wrangler::debug("CTRL+-: View Zoom-Out: ");
863  
864 # emit appropriate event
865 $filebrowser->{wrangler}->publish('zoom.out');
866 }elsif($keycode == 48){
867 Wrangler::debug("CTRL+0: View Zoom-Standard: ");
868  
869 # emit appropriate event
870 $filebrowser->{wrangler}->publish('zoom.standard');
871 }elsif($keycode == WXK_ESCAPE){
872 if($filebrowser->{in_viewmode}){
873 Wrangler::debug("ESC: Filebrowser is viewing: so close Viewer.");
874 # $filebrowser->{viewer}->Close();
875 # $filebrowser->Show(1);
876 }else{
877 Wrangler::debug("ESC: Deselect all");
878 $filebrowser->DeselectAll();
879 }
880 }elsif($keycode == WXK_F2){
881 Wrangler::debug("F2: Rename");
882  
883 $filebrowser->Rename();
884 }elsif($keycode == WXK_DELETE){
885 Wrangler::debug("Delete");
886  
887 $filebrowser->Delete();
888 }
889  
890 $event->Skip(1);
891 }
892  
893  
894 sub ForkAndExec {
895 my @commands = @_;
896  
897 my $pid = fork();
898  
899 print STDERR "unable to fork: $!" unless defined($pid);
900 return undef unless defined($pid);
901  
902 # contains no pid when we're in the forked child
903 if(!$pid){
904 exec(@commands);
905 die "unable to exec: $!";
906 }
907  
908 return $pid if $pid;
909 }
910  
911 sub Destroy {
912 my $self = shift;
913  
914 Wrangler::PubSub::unsubscribe_owner(__PACKAGE__);
915  
916 $self->SUPER::Destroy();
917 }
918  
919 1;