blib/lib/Gtk2/Ex/TickerView.pm

filter: Statementstmt 91.3% 21 / 23 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.5% 29 / 31 CC 1 SCAR 0.4
CC
1
Cov
91%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 # Copyright 2007, 2008, 2009, 2010, 2011, 2017, 2019 Kevin Ryde
2  
3 # This file is part of Gtk2-Ex-TickerView.
4 #
5 # Gtk2-Ex-TickerView is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 3, or (at your option) any later
8 # version.
9 #
10 # Gtk2-Ex-TickerView is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 # for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with Gtk2-Ex-TickerView. If not, see <http://www.gnu.org/licenses/>.
17  
18 package Gtk2::Ex::TickerView;
19 4 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 4 ▶use List::Util qw(min max);
Subroutine BEGIN: called CC=1 SCAR=0.0
24 4 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
25 4 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 0 ▶use Glib;
Subroutine BEGIN: called CC=1 SCAR=2.6
28 # version 1.180 for Gtk2::CellLayout as an interface, also 1.180 for
29 # Gtk2::Buildable overriding superclass interface
30 use Gtk2 1.180;
31  
32 use Gtk2::Ex::SyncCall 12; # version 12 for gtk XID workaround
33 use Gtk2::Ex::CellLayout::Base 4; # version 4 for _cellinfo_starts()
34 our @ISA;
35 push @ISA, 'Gtk2::Ex::CellLayout::Base';
36  
37 our $VERSION = 16;
38  
39 # set this to 1 for some diagnostic prints, or 2 for even more prints
40 use constant DEBUG => 0;
41  
42 use constant { DEFAULT_FRAME_RATE => 4, # times per second
43 DEFAULT_SPEED => 30, # pixels per second
44 };
45  
46 # not wrapped until Gtk2-Perl 1.200
47 use constant GDK_PRIORITY_REDRAW => (Glib::G_PRIORITY_HIGH_IDLE + 20);
48  
49 use Glib::Object::Subclass
50 'Gtk2::DrawingArea',
51 interfaces =>
52 [ 'Gtk2::CellLayout',
53 # Gtk2::Buildable new in Gtk 2.12, omit if not available
54 Gtk2::Widget->isa('Gtk2::Buildable') ? ('Gtk2::Buildable') : ()
55 ],
56  
57 signals => { expose_event => \&_do_expose_event,
58 size_request => \&_do_size_request,
59 size_allocate => \&_do_size_allocate,
60 button_press_event => \&_do_button_press_event,
61 motion_notify_event => \&_do_motion_notify_event,
62 button_release_event => \&_do_button_release_event,
63 scroll_event => \&_do_scroll_event,
64 visibility_notify_event => \&_do_visibility_notify_event,
65 direction_changed => \&_do_direction_changed,
66 map => \&_do_map_or_unmap,
67 unmap => \&_do_map_or_unmap,
68 unrealize => \&_do_unrealize,
69 notify => \&_do_notify,
70 state_changed => \&_do_state_or_style_changed,
71 style_set => \&_do_state_or_style_changed,
72 },
73 properties => [ Glib::ParamSpec->object
74 ('model',
75 'Model object',
76 'TreeModel giving the items to display.',
77 'Gtk2::TreeModel',
78 Glib::G_PARAM_READWRITE),
79  
80 Glib::ParamSpec->boolean
81 ('run',
82 'Run ticker',
83 'Whether to run the ticker, ie. scroll across.',
84 1, # default yes
85 Glib::G_PARAM_READWRITE),
86  
87 Glib::ParamSpec->double
88 ('speed',
89 'Speed',
90 'Speed to move the items across, in pixels per second.',
91 0, POSIX::DBL_MAX(),
92 DEFAULT_SPEED,
93 Glib::G_PARAM_READWRITE),
94  
95 Glib::ParamSpec->double
96 ('frame-rate',
97 'Frame rate',
98 'How many times per second to move for scrolling.',
99 0, POSIX::DBL_MAX(),
100 DEFAULT_FRAME_RATE,
101 Glib::G_PARAM_READWRITE),
102  
103 Glib::ParamSpec->boolean
104 ('fixed-height-mode',
105 'Fixed height mode',
106 'Assume all cells have the same desired height.',
107 0, # default no
108 Glib::G_PARAM_READWRITE),
109  
110 Glib::ParamSpec->enum
111 ('orientation',
112 (do { # translation from GtkOrientable
113 my $str = 'Orientation';
114 eval { require Locale::Messages;
115 Locale::Messages::dgettext('gtk20-properties',$str)
116 } || $str }),
117 'Horizontal or vertical display and scrolling.',
118 'Gtk2::Orientation',
119 'horizontal',
120 Glib::G_PARAM_READWRITE),
121  
122 ];
123  
124 # The private per-object fields are:
125 #
126 # vertical 0 or 1
127 # 0 when horizontal, 1 when vertical. Presented through GET_PROPERTY
128 # and SET_PROPERTY as Gtk2::Orientation 'horizontal' and 'vertical', but
129 # internally the number allows computed indexes instead of conditionals.
130 #
131 # pixmap Gtk2::Gdk::Pixmap or undef
132 # Established in _pixmap(), undef until then.
133 #
134 # pixmap_size
135 # The width of pixmap when horizontal, or height when vertical. This is
136 # established by _pixmap_desired_size() and thus may be set before
137 # pixmap is actually created.
138 #
139 # row_widths hashref { $index => $width }
140 # $index is an integer row number. $width is the total width of all the
141 # renderers' drawing of that row.
142 #
143 # This is a hash instead of an array so as to keep widths for roughly
144 # just the rows displayed, which may be a good thing on a big model.
145 # Widths are discarded when _pixmap_shift drops rows off the left edge,
146 # and when _pixmap_empty purges the whole pixmap. Widths are stored by
147 # _pixmap_extend, so the displayed rows are present, ready for
148 # _normalize() to use contemplating an increment of want_index.
149 #
150 # Widths are also saved by normalize actions like a big scroll_pixels()
151 # or a get_path_at_pos() of an off-screen position. Those widths end up
152 # remaining until a full redraw or until shifting passes them by. Which
153 # is probably no bad thing if one off-screen position calculation is
154 # reasonably likely to be followed by another. Might be worth thinking
155 # more about that though.
156 #
157 # The widths of drawn rows are implicitly in drawn_array as the
158 # difference between successive $x values, so having them in
159 # 'row_widths' is a bit of duplication. If _normalize() looked at
160 # drawn_array the drawn rows could be omitted, but almost certainly the
161 # code size would outweigh the data space.
162 #
163 # drawn_array arrayref [ $index, $x, $index, $x, ... ]
164 # Each $index is an integer row number. Each $x is the position in
165 # 'pixmap' where row $index has been drawn. There's two things helped
166 # by saveing all drawn positions,
167 #
168 # 1. _pixmap_shift() is easier. It can decrement each $x by the shift
169 # amount and look for the last $x <= 0 as the drawn rows retained.
170 # When the last row has been chopped off at the right edge (which is
171 # almost always) the second last position is immediately available to
172 # become pixmap_end_x, and the last index is pixmap_end_index to
173 # extend from.
174 #
175 # If all positions weren't recorded then _pixmap_shift() would have
176 # to reconstruct them to find that $x <= 0 point and the second last
177 # row pos, by adding up row widths.
178 #
179 # 2. _pixmap_find_want() can contemplate two drawn copies of a given
180 # row. There might be one at the start which starts a bit off screen
181 # at the left, and another later in the pixmap. When want_x allows
182 # the first to be used it makes best use of the current pixmap
183 # contents. If not then the second is a fallback and if it's too far
184 # to the right then might still be usable if _pixmap_shift() moves it
185 # down.
186 #
187 # Point 2 might be covered by retaining two positions for each row: its
188 # leftmost and then second leftmost (if any). _pixmap_shift() would
189 # still be tricky though, if it tried to find a new second leftmost for
190 # those rows whose leftmost had gone off-screen.
191 #
192 # Rows of zero width are still entered in drawn_array. This ensures
193 # _do_row_changed, _do_row_deleted, etc, notice that those rows are
194 # on-screen. It's possible want_index is a zero width row if an
195 # explicit scroll_to_start has gone there (or a hypothetical
196 # scroll_to_iter or something like that). _normalize() normally doesn't
197 # leave want_index on a zero width when moving though.
198 #
199 # want_x, want_index integers
200 # want_index is the desired row number (counting from 0) to be shown at
201 # the start of the ticker window. want_x is an x position where the
202 # left edge of the want_index row should start. want_x is zero or
203 # negative. Negative means the want_index item is partly off the left
204 # edge.
205 #
206 # Scrolling will soon make want_x a larger negative than the width of
207 # the want_index row. Expose (using _normalize()) looks for that and
208 # moves up by incrementing want_index and adding the skipped row width
209 # to want_x. It can go across multiple rows that way if necessary.
210 #
211 # Scrolling backwards can make want_x go positive. _normalize_want()
212 # and _normalize() again adjust, this time by decrementing want_index to
213 # a preceding row and subtracting that width from want_x, working back
214 # to find what row should be at or just before the left edge.
215 #
216 # pixmap_end_x
217 # The x just after the endmost drawn part of the pixmap. pixmap_end_x
218 # is truncated to pixmap_size when full or when the model is empty or
219 # all zero width rows.
220 #
221 # Until pixmap_end_x is faked to pixmap_size it's equal to the last
222 # drawn_array entry plus that entry's row_width. But the fakery to
223 # pixmap_size means it's easier to maintain pixmap_end_x separately than
224 # to build from drawn_array each time.
225 #
226 # The pixmap starts with only as much content as needed for expose to
227 # show the expose region the want_index/want_x position. As
228 # want_x,want_index advance _pixmap_extend() draws more content at
229 # pixmap_end_x.
230 #
231 # The "undrawn" area from pixmap_end_x onwards is always cleared to the
232 # background colour (in _pixmap_redraw() and _pixmap_shift()), so
233 # _pixmap_extend() can just draw. Some of that area might never be used
234 # but the idea is to do a single big XDrawRectangle instead of several
235 # small ones.
236 #
237 # visibility_state Gtk2::Gdk::VisibilityState enum string or 'initial'
238 # This is maintained from the 'visiblity-notify-event' handler. If
239 # 'fully-obscured' then the scroll timer is stopped, to save a bit of
240 # work when nothing can be seen.
241 #
242 # drag_xy arrayref [ $root_x, $root_y ]
243 # During a drag this is the last position of the mouse, in root window
244 # coordinates. When not in drag 'drag_xy' is not in $self at all. The
245 # timer is stopped while drag_xy is set. Only one of the two x or y are
246 # used, according to 'vertical', but storing not much extra and it
247 # smoothly handles the slightly freaky case of a change of orientation
248 # in the middle of a drag.
249 #
250 # model_empty boolean
251 # True when we believe $self->{'model'} is empty. Initialized in
252 # SET_PROPERTY when the model is first set, then kept up to date in
253 # _do_row_inserted() and _do_row_deleted().
254 #
255 # The aim of this is to give _do_row_inserted() a way to be sure when
256 # the model transitions from empty to non-empty, which provokes a resize
257 # and a possible timer restart.
258 #
259 # Testing for model length == 1 in _do_row_inserted() would be very
260 # nearly enough, but not perfect. If an earlier connected row-inserted
261 # handler inserts yet another row in response to the first insertion
262 # then by the time _do_row_inserted() runs it sees length==2. This
263 # would be pretty unusual, and probably needs 'iters-persist' on the
264 # model for the first iter to remain valid past the extra model change,
265 # but it's not completely outrageous.
266 #
267 # In RtoL mode all the x positions are measured from the right edge of the
268 # window or pixmap instead. Only the expose and the cell renderer drawing
269 # must mirror those RtoL logical positions into LtoR screen coordinates.
270 #
271 # In vertical orientation the "x" values are in fact y positions and the
272 # "width"s are in fact heights. Stand by for a search and replace to
273 # something neutral like "p" and "size" or whatever :-).
274 #
275  
276 sub INIT_INSTANCE {
277 my ($self) = @_;
278  
279 # the offscreen 'pixmap' already works as a form of double buffering, no
280 # need for DBE
281 $self->set_double_buffered (0);
282  
283 $self->{'want_index'} = 0;
284 $self->{'want_x'} = 0;
285 $self->{'row_widths'} = {};
286 $self->{'drawn_array'} = [];
287 $self->{'pixmap_end_x'} = 0;
288 $self->{'visibility_state'} = 'initial';
289 $self->{'run'} = 1; # default yes
290 $self->{'frame_rate'} = DEFAULT_FRAME_RATE;
291 $self->{'speed'} = DEFAULT_SPEED;
292 $self->{'vertical'} = 0;
293
294 $self->add_events (['visibility-notify-mask',
295 'button-press-mask',
296 'button-motion-mask',
297 'button-release-mask']);
298 }
299  
300 sub GET_PROPERTY {
301 my ($self, $pspec) = @_;
302 my $pname = $pspec->get_name;
303 if ($pname eq 'orientation') {
304 return ($self->{'vertical'} ? 'vertical' : 'horizontal');
305 } else {
306 return $self->{$pname};
307 }
308 }
309  
310 sub SET_PROPERTY {
311 my ($self, $pspec, $newval) = @_;
312 my $pname = $pspec->get_name;
313 my $oldval = $self->{$pname};
314 ### SET_PROPERTY: $pname, $newval
315  
316 if ($pname eq 'orientation') {
317 $oldval = $self->{'vertical'};
318 $self->{'vertical'} = $newval = ($newval eq 'horizontal' ? 0 : 1);
319  
320 } else {
321 $self->{$pname} = $newval;
322  
323 if ($pname eq 'model') {
324 if (($oldval||0) == ($newval||0)) {
325 # no change, avoid resize, redraw, etc
326 return;
327 }
328 my $model = $newval;
329 $self->{'model_empty'} = ! ($model && $model->get_iter_first);
330 $self->{'model_ids'} = $model && do {
331 Scalar::Util::weaken (my $weak_self = $self);
332 my $ref_weak_self = \$weak_self;
333  
334 require Glib::Ex::SignalIds;
335 Glib::Ex::SignalIds->new
336 ($model,
337 $model->signal_connect (row_changed => \&_do_row_changed,
338 $ref_weak_self),
339 $model->signal_connect (row_inserted => \&_do_row_inserted,
340 $ref_weak_self),
341 $model->signal_connect (row_deleted => \&_do_row_deleted,
342 $ref_weak_self),
343 $model->signal_connect (rows_reordered => \&_do_rows_reordered,
344 $ref_weak_self))
345 };
346 }
347 }
348  
349 # updates ...
350  
351 # 'fixed_height_mode' turned to false provokes a resize, so as to look at
352 # all the rows now, not just the first. But don't resize when turning
353 # fixed_height_mode to true since the size we have is based on all rows
354 # and if the first row is truely representative then its size is the same
355 # as already in use.
356 #
357 if ($pname eq 'model'
358 || ($pname eq 'orientation' && $oldval != $newval)) {
359 ### model or orientation change
360 %{$self->{'row_widths'}} = ();
361 $self->queue_resize;
362 _pixmap_queue_draw ($self); # zap pixmap contents
363 }
364  
365 if ($pname eq 'fixed_height_mode' && $oldval && ! $newval) {
366 $self->queue_resize;
367 }
368  
369 if ($pname eq 'model' || $pname eq 'run' || $pname eq 'frame_rate') {
370 if ($pname eq 'frame_rate') {
371 # Discard old timer ready for new rate. Might like to carry over the
372 # elapsed period in the old one, but it should be short enough not to
373 # matter, and Glib doesn't seem to have much to help such a
374 # calculation.
375 delete $self->{'timer'};
376 }
377 _update_timer ($self);
378 }
379 }
380  
381  
382 #------------------------------------------------------------------------------
383 # size desired and allocated
384  
385 # 'size-request' class closure
386 sub _do_size_request {
387 my ($self, $req) = @_;
388 ### TickerView _do_size_request()
389  
390 $req->width (0);
391 $req->height (0);
392  
393 my $model = $self->{'model'} || return; # no size if no model
394 my @cells = $self->GET_CELLS;
395 @cells || return; # no size if no cells
396  
397 my $sizefield = 3 - $self->{'vertical'}; # width vert, height horiz
398 my $want_size = 0;
399 for (my $iter = $model->get_iter_first;
400 $iter;
401 $iter = $model->iter_next ($iter)) {
402 $self->_set_cell_data ($iter);
403 foreach my $cell (@cells) {
404 $want_size = max ($want_size,
405 ($cell->get_size($self,undef))[$sizefield]);
406 }
407 if ($self->{'fixed_height_mode'}) {
408 ### one row only for fixed-height-mode
409 last;
410 }
411 }
412  
413 if ($sizefield == 3) {
414 $req->height ($want_size);
415 } else {
416 $req->width ($want_size);
417 }
418 ### decide size: $req->width."x".$req->height
419 }
420  
421 # 'size_allocate' class closure
422 #
423 # This is also reached for cell renderer and attribute changes through
424 # $self->queue_resize in CellLayout::Base.
425 #
426 # For a move without a resize the pixmap at its current size could be
427 # retained. Probably moves alone won't occur often enough to make that
428 # worth worrying about.
429 #
430 # Crib: no queue_draw() here, since the default redraw_on_alloc means that's
431 # done automatically (in gtk_widget_size_allocate()).
432 #
433 sub _do_size_allocate {
434 my ($self, $alloc) = @_;
435 ### TickerView _do_size_allocate()
436  
437 $self->signal_chain_from_overridden ($alloc);
438  
439 if (my $pixmap = $self->{'pixmap'}) {
440 my ($want_width, $want_height) = _pixmap_desired_size ($self, $alloc);
441 my ($got_width, $got_height) = $pixmap->get_size;
442 if ($want_width != $got_width || $want_height != $got_height) {
443 ### want new pixmap size
444 $self->{'pixmap'} = undef;
445 _pixmap_queue_draw ($self);
446 return;
447 }
448 }
449 }
450  
451  
452 #-----------------------------------------------------------------------------
453 # expose and pixmap
454  
455 # 'expose-event' class closure, getting Gtk2::Gdk::Event::Expose
456 sub _do_expose_event {
457 my ($self, $event) = @_;
458 if (DEBUG >= 2) {
459 my $expose_size = ($self->{'vertical'}
460 ? $event->area->y + $event->area->height
461 : $event->area->x + $event->area->width);
462 print "TickerView _do_expose_event count=",$event->count,
463 " pixmap_redraw=",($self->{'pixmap_redraw'}?"yes":"no"),
464 " expose_size=$expose_size\n";
465 }
466  
467 my $expose_size = do { my $expose_rect = $event->area;
468 ($self->{'vertical'}
469 ? $expose_rect->y + $expose_rect->height
470 : $expose_rect->x + $expose_rect->width) };
471 my $pixmap = _pixmap($self);
472  
473 my $x;
474 if ($self->{'pixmap_redraw'}
475 || ! defined ($x = _pixmap_find_want ($self, $expose_size))) {
476 # want_index/want_x isn't in the pixmap at all
477 _pixmap_empty ($self);
478 $x = 0;
479  
480 } elsif ($x + $expose_size > $self->{'pixmap_size'}) {
481 # want_index/want_x is in the pixmap, but there's not enough space after
482 # it for the $expose_size
483 if (DEBUG >= 2) { print "expose found $x but +$expose_size =",
484 $x + $expose_size,
485 " is past $self->{'pixmap_size'}, so shift\n"; }
486 _pixmap_shift ($self, $x);
487 $x = 0;
488 }
489 _pixmap_extend ($self, $x + $expose_size);
490  
491 if ($self->get_direction eq 'rtl') {
492 # width when horiz, height when vert
493 my $win_size = ($self->allocation->values)[2 + $self->{'vertical'}];
494 $x = $self->{'pixmap_size'} - 1 - $win_size - $x;
495 }
496 my $win = $self->window;
497 my $gc = $self->get_style->black_gc; # any gc for an XCopyArea
498 $gc->set_clip_region ($event->region);
499 $win->draw_drawable ($gc, $pixmap,
500 ($self->{'vertical'} ? (0,$x) : ($x,0)), # src
501 0,0, # dst
502 $win->get_size);
503 $gc->set_clip_region (undef);
504 return 0; # Gtk2::EVENT_PROPAGATE
505 }
506  
507 sub _pixmap_find_want {
508 my ($self, $expose_size) = @_;
509 if (DEBUG >= 2) { print " _pixmap_find_want",
510 " want_index=$self->{'want_index'}",
511 " want_x=$self->{'want_x'}\n"; }
512  
513 # the usual case here is _normalize() finding want_index still within its
514 # row width and the previously determined drawn_want_at in drawn_array is
515 # still entirely in a drawn portion of the pixmap
516  
517 my ($want_x, $want_index)
518 = _normalize ($self, $self->{'want_x'}, $self->{'want_index'});
519 if (! defined $want_x) {
520 # no model, or model empty, or all rows zero width
521 return ($self->{'want_x'} = 0);
522 }
523 $self->{'want_x'} = $want_x;
524 $self->{'want_index'} = $want_index;
525  
526 $want_x = POSIX::floor ($want_x);
527 my $drawn = $self->{'drawn_array'};
528 my ($i, $x);
529  
530 # see if the cached 'drawn_want_at' is still the wanted index and in range
531 if (defined ($i = $self->{'drawn_want_at'})
532 && defined $drawn->[$i]
533 && $drawn->[$i] == $want_index
534 && ($x = $drawn->[$i+1] - $want_x) >= 0
535 && $x + $expose_size <= $self->{'pixmap_size'}) {
536 if (DEBUG >= 2) { print " drawn_want_at still good\n"; }
537 return $x;
538 }
539  
540 if (DEBUG >= 2) { print " seeking leftmost $want_index\n"; }
541 for ($i = 0; $i < @$drawn; $i+=2) {
542 if ($drawn->[$i] == $want_index
543 && (($x = $drawn->[$i+1] - $want_x) >= 0)) {
544 $self->{'drawn_want_at'} = $i;
545 return $x;
546 }
547 }
548 if (DEBUG >= 2) { local $,=' '; print " not found in",@$drawn,"\n"; }
549 return undef;
550 }
551  
552 sub _pixmap_empty {
553 my ($self) = @_;
554 if (DEBUG) { print "_pixmap_empty to",
555 " want_index=$self->{'want_index'},",
556 "want_x=$self->{'want_x'}\n"; }
557  
558 $self->{'pixmap_redraw'} = 0;
559 my $pixmap = _pixmap($self);
560 my ($pixmap_width, $pixmap_height) = $pixmap->get_size;
561 my $gc = $self->get_style->bg_gc ($self->state);
562 $pixmap->draw_rectangle ($gc, 1, 0,0, $pixmap_width,$pixmap_height);
563  
564 @{$self->{'drawn_array'}} = ();
565 $self->{'drawn_want_at'} = undef;
566 %{$self->{'row_widths'}} = (); # prune
567  
568 $self->{'pixmap_end_x'} = POSIX::floor ($self->{'want_x'});
569 }
570  
571 sub _pixmap_shift {
572 my ($self, $offset) = @_;
573 if (DEBUG >= 2) {
574 print "_pixmap_shift offset=$offset, from",
575 " pixmap_end_x=",(defined $self->{'pixmap_end_x'} ? $self->{'pixmap_end_x'} : 'undef'),
576 "\n";
577 }
578 my $pixmap_size = $self->{'pixmap_size'};
579 my $drawn = $self->{'drawn_array'};
580  
581 # if the rightmost drawn goes past the end of the pixmap then discard it
582 if (@$drawn
583 && $drawn->[-1] + _row_width($self,$drawn->[-2]) > $pixmap_size) {
584 if (DEBUG >= 2) { print " last index=$drawn->[-2] past end, drop it\n"; }
585 $self->{'pixmap_end_x'} = pop @$drawn;
586 pop @$drawn; # index
587 if (! @$drawn) { goto \&_pixmap_empty; }
588 }
589  
590 my %prune_row_widths; # keys are the indexes to be discarded
591 my $last_nonpositive = 0;
592 for (my $i = 0; $i < @$drawn; $i+=2) {
593 if (($drawn->[$i+1] -= $offset) <= 0) {
594 $last_nonpositive = $i;
595 $prune_row_widths{$drawn->[$i]} = 1;
596 } else {
597 delete $prune_row_widths{$drawn->[$i]};
598 }
599 }
600 my $end_x = ($self->{'pixmap_end_x'} -= $offset);
601 splice @$drawn, 0, $last_nonpositive;
602  
603 # row_widths for rows shifted off at the left are dropped, unless they
604 # also occur later in the drawn contents
605 delete $prune_row_widths{$drawn->[0]};
606 delete @{$self->{'row_widths'}} {keys %prune_row_widths}; # hash slice
607 if (DEBUG >= 2) {
608 local $,=' '; print " prune row widths:", keys %prune_row_widths,"\n";
609 }
610 # CHECK-ME: probably not supposed to shift down to nothing ...
611 if (! @$drawn) { goto \&_pixmap_empty; }
612  
613 if (DEBUG >= 2) { local $,=' '; print " now drawn",@$drawn,"\n"; }
614  
615 my $pixmap = $self->{'pixmap'};
616 my ($pixmap_width, $pixmap_height) = $pixmap->get_size;
617 my $gc = $self->get_style->bg_gc ($self->state);
618  
619 # $end_x shouldn't be negative, but apply clamp $copy_size just in case.
620 # Won't have $offset==0, thus won't have $src_x==$dst_x, so no sort circuits.
621 #
622 my $copy_size = max ($end_x, 0);
623 my $clear_size = $pixmap_size - $copy_size;
624 my ($src_x, $dst_x, $clear_x);
625 if ($self->get_direction eq 'ltr') {
626 # $pixmap_size
627 # +------+----------------+----+
628 # | | $copy_size | |
629 # +------+----------------+----+
630 # $offset $end_x --> measuring rightwards
631 # / /
632 # +----------------+-----------+
633 # | $copy_size |$clear_size|
634 # +----------------+-----------+
635 #
636 $dst_x = 0;
637 $src_x = $offset;
638 $clear_x = $copy_size;
639 } else {
640 # $pixmap_size
641 # +----+----------------+------+
642 # | | $copy_size | |
643 # +----+----------------+------+
644 # $end_x $offset <-- measuring leftwards
645 # \ \
646 # +-----------+----------------+
647 # |$clear_size| $copy_size |
648 # +-----------+----------------+
649 #
650 $dst_x = $clear_size;
651 $src_x = $dst_x - $offset;
652 $clear_x = 0;
653 }
654 if (DEBUG >= 2) { print " copy $src_x to $dst_x size=$copy_size\n";
655 print " clear $clear_x size=$clear_size\n"; }
656  
657 if ($self->{'vertical'}) {
658 $pixmap->draw_drawable ($gc, $pixmap,
659 0,$src_x, # src
660 0,$dst_x, # dst
661 $pixmap_width, $copy_size); # width,height
662 # clear the remainder
663 $pixmap->draw_rectangle ($gc, 1,
664 0,$clear_x,
665 $pixmap_width, $clear_size);
666 } else {
667 # horizontal
668 $pixmap->draw_drawable ($gc, $pixmap,
669 $src_x,0, # src
670 $dst_x,0, # dst
671 $copy_size, $pixmap_height); # width,height
672 # clear the remainder
673 $pixmap->draw_rectangle ($gc, 1,
674 $clear_x,0,
675 $clear_size, $pixmap_height);
676 }
677 }
678  
679 # draw more at 'pixmap_end_x' to ensure it's not less than $target_x
680 sub _pixmap_extend {
681 my ($self, $target_x) = @_;
682 if (DEBUG >= 2) {
683 my $last_index = $self->{'drawn'}->[-2];
684 my $pixmap_size = $self->{'pixmap_size'};
685 print "_pixmap_extend target_x=$target_x",
686 " got last index=",(defined $last_index?$last_index:'undef'),
687 ",x=$self->{'pixmap_end_x'}",
688 ", pixmap_size=",(defined $pixmap_size ? $pixmap_size : '[undef]'),
689 "\n";
690 }
691 if (DEBUG) {
692 if ($target_x > $self->{'pixmap_size'}) {
693 die "oops, target_x=$target_x bigger than pixmap ",
694 $self->{'pixmap_size'};
695 }
696 }
697  
698 my $x = $self->{'pixmap_end_x'};
699 if ($x >= $target_x) { return; } # if target already covered
700  
701 my $pixmap = _pixmap($self);
702 my ($pixmap_width, $pixmap_height) = $pixmap->get_size;
703 my $pixmap_size = $self->{'pixmap_size'};
704  
705 my $model = $self->{'model'};
706 if (! $model) {
707 ### no model set
708 EMPTY:
709 $self->{'pixmap_end_x'} = $pixmap_size;
710 return;
711 }
712  
713 # "pack_start"s first then "pack_end"s
714 my @cellinfo_list = ($self->_cellinfo_starts,
715 reverse $self->_cellinfo_ends);
716 if (! @cellinfo_list) {
717 ### no cell renderers to draw with
718 goto EMPTY;
719 }
720  
721 my $all_zeros = _make_all_zeros_proc();
722 my $ltor = ($self->get_direction eq 'ltr');
723 my $row_widths = $self->{'row_widths'};
724 my $drawn = $self->{'drawn_array'};
725 my $vertical = $self->{'vertical'};
726  
727 my $index = $drawn->[-2];
728 if (defined $index) {
729 $index++;
730 } else {
731 $index = $self->{'want_index'};
732 }
733 my $iter = $model->iter_nth_child (undef, $index);
734  
735 for (;;) {
736 if (! $iter) {
737 # initial $index was past the end, or stepped iter_next() past the
738 # end, either way wrap around
739 $index = 0;
740 $iter = $model->get_iter_first;
741 if (! $iter) {
742 ### model has no rows
743 $x = $pixmap_size;
744 last;
745 }
746 }
747  
748 push @$drawn, $index, $x;
749 $self->_set_cell_data ($iter);
750  
751 my $row_size = 0;
752 foreach my $cellinfo (@cellinfo_list) {
753 my $cell = $cellinfo->{'cell'};
754 if (! $cell->get('visible')) { next; }
755  
756 my (undef, undef, $width, $height) = $cell->get_size ($self, undef);
757 my $rect;
758 if ($vertical) {
759 $rect = Gtk2::Gdk::Rectangle->new
760 (0, $ltor ? $x : $pixmap_height - 1 - $x - $height,
761 $pixmap_width, $height);
762 $x += $height;
763 $row_size += $height;
764 } else {
765 $rect = Gtk2::Gdk::Rectangle->new
766 ($ltor ? $x : $pixmap_width - 1 - $x - $width, 0,
767 $width, $pixmap_height);
768 $x += $width;
769 $row_size += $width;
770 }
771 $cell->render ($pixmap, $self, $rect, $rect, $rect, []);
772 }
773  
774 $row_widths->{$index} = $row_size;
775 if (DEBUG >= 2) { print " draw $index at x=",$x-$row_size,
776 " width $row_size\n"; }
777  
778 if ($all_zeros->($index, $row_size)) {
779 ### all cell widths on all rows are zero
780 $self->{'want_x'} = 0;
781 $x = $pixmap_size;
782 last;
783 }
784  
785 $index++;
786 if ($x >= $target_x) { last; } # stop when target covered
787 $iter = $model->iter_next ($iter);
788 }
789  
790 $self->{'pixmap_end_x'} = min ($x, $pixmap_size);
791 ### extended to pixmap_end_x: $self->{'pixmap_end_x'}
792 }
793  
794 # _pixmap() returns 'pixmap', creating it if it doesn't already exist.
795 # The height is the same as the window height.
796 # The width is 1.5 * the window width, or half the screen width, whichever
797 # is bigger.
798 #
799 # The pixmap is designed to avoid drawing the same row repeatedly as it
800 # scrolls across. The wider the pixmap the less often a full redraw will be
801 # needed. The width used is therefore a compromise between the memory taken
802 # by a wide pixmap, versus redraws caused by a narrow pixmap.
803 #
804 # Twice the window width gives a reasonable amount of hidden pixmap
805 # buffering off the window ends. However if the window is unusually narrow
806 # it could be much less than a typical row, so impose a minimum of half the
807 # screen width.
808 #
809 # (Maybe a maximum of say twice the screen width could be imposed too, so
810 # that a hugely wide window doesn't result in a massive pixmap. But for a
811 # pixmap smaller than the window we'd have to notice what portion of the
812 # window is on-screen. Probably that's much more trouble than it's worth.
813 # If you ask for a stupidly wide window then expect to have your pixmap
814 # memory used up. :-)
815 #
816 sub _pixmap {
817 my ($self) = @_;
818 return ($self->{'pixmap'} ||= do {
819 ### _pixmap() create
820 my ($pixmap_width, $pixmap_height)
821 = _pixmap_desired_size ($self, $self->allocation);
822 ### create size: "${pixmap_width}x${pixmap_height}"
823 Gtk2::Gdk::Pixmap->new ($self->window, $pixmap_width, $pixmap_height, -1);
824 });
825 }
826 use constant _PIXMAP_ALLOCATION_FACTOR => 1.5;
827 use constant _SCREEN_SIZE_FACTOR => 0.5;
828 sub _pixmap_desired_size {
829 my ($self, $alloc) = @_;
830 ### _pixmap_desired_size()
831 my @pixmap_dims = ($alloc->width, $alloc->height);
832 my $i = $self->{'vertical'}; # width for horiz, height for vert
833 my $screen = $self->get_screen; # gtk 2.4 for celllayout, so have 2.2 screen
834 my @screen_dims = ($screen->get_width, $screen->get_height);
835  
836 ### max: "alloc*"._PIXMAP_ALLOCATION_FACTOR." = ".($pixmap_dims[$i] * _PIXMAP_ALLOCATION_FACTOR)
837 ### max: "screen*"._SCREEN_SIZE_FACTOR." = ".($screen_dims[$i] * _SCREEN_SIZE_FACTOR)
838 $pixmap_dims[$i] = $self->{'pixmap_size'}
839 = int (max ($pixmap_dims[$i] * _PIXMAP_ALLOCATION_FACTOR,
840 $screen_dims[$i] * _SCREEN_SIZE_FACTOR));
841 ### desire: "$pixmap_dims[0]x$pixmap_dims[1]"
842 return @pixmap_dims;
843 }
844  
845 sub _pixmap_queue_draw {
846 my ($self) = @_;
847 ### _pixmap_queue_draw()
848 # zap 'drawn_array' to save work in _apply_remap
849 $self->{'pixmap_redraw'} = 1;
850 @{$self->{'drawn_array'}} = ();
851 $self->queue_draw;
852 }
853  
854 #-----------------------------------------------------------------------------
855 # row index widths and normalization
856  
857 # Normalize $x,$index so that $x<=0 and $x+$row_width >= 0.
858 # The return is two new values ($x,$index).
859 # If $x==0 then $x,$index are returned unchanged.
860 # If there's no model, or the model is empty, the return is empty ().
861 # If all rows are zero width the return is $x==undef and $index unchanged.
862 #
863 sub _normalize {
864 my ($self, $x, $index) = @_;
865  
866 my $model = $self->{'model'} || return;
867 my $all_zeros = _make_all_zeros_proc();
868 my $len = $model->iter_n_children(undef) || return; # if model empty
869  
870 if ($x < 0) {
871 # Here we're looking to see if the want_index row is entirely
872 # off-screen, ie. if want_x + row_width (of that row) would still be
873 # want_x <= 0.
874 #
875 # If _row_width() gives us a $iter, because it used it to get a row
876 # width, then we keep it going for further rows. If _row_width()
877 # operates out of its cache then there's no iter.
878 #
879 ### forward from: "$index,$x"
880 my $iter;
881  
882 for (;;) {
883 my $row_width = _row_width ($self, $index, $iter);
884 if ($x + $row_width > 0) {
885 last;
886 }
887 if ($all_zeros->($index, $row_width)) {
888 ### all cell widths on all rows are zero
889 return (undef, $_[2]); # with original $index
890 }
891 $x += $row_width;
892 $index++;
893 if ($index >= $len) {
894 $index = 0;
895 $iter = undef;
896 } else {
897 if ($iter) {
898 $iter = $model->iter_next ($iter);
899 }
900 }
901 }
902  
903 } else {
904 # Here we're trying to bring $x back to <= 0, usually because a backward
905 # scroll has pushed our want_x position to the right and we have to see
906 # what the preceding row is and want position to draw it.
907 #
908 # Because there's no "iter_prev" there's no use of iters here, it ends
909 # up a new iter_nth_child in _row_width() for every row not already
910 # cached. For a user scroll back just a short distance the previous row
911 # is probably already cached (and even probably in the pixmap).
912 #
913 ### backward from: "$x,$index"
914  
915 while ($x > 0) {
916 $index--;
917 if ($index < 0) {
918 $index = max (0, $len-1);
919 }
920 my $row_width = _row_width ($self, $index);
921 if ($all_zeros->($index, $row_width)) {
922 ### all cell widths on all rows are zero
923 return (undef, $_[2]); # with original $index
924 }
925 $x -= $row_width;
926 }
927 }
928 #### now at "$index,$x"
929 return ($x, $index);
930 }
931  
932 # Return the width in pixels of row $index, or height when vertical.
933 # $iter is an iterator for $index, or undef to make one here if necessary.
934 # If an iterator is made then it's stored back to $_[2], as call-by-reference.
935 #
936 sub _row_width {
937 my ($self, $index, $iter) = @_;
938  
939 my $row_widths = $self->{'row_widths'};
940 my $row_width = $row_widths->{$index};
941 if (defined $row_width) { return $row_width; }
942  
943 if (DEBUG) { print " _row_width on $index, iter=",
944 (defined $iter ? $iter : 'undef'), "\n"; }
945 if (! defined $iter) {
946 my $model = $self->{'model'};
947 $iter = $_[2] = $model && $model->iter_nth_child (undef, $index);
948 if (! defined $iter) {
949 if (DEBUG) { print " _row_width index $index out of range\n"; }
950 return 0;
951 }
952 }
953 $self->_set_cell_data ($iter);
954  
955 my $sizefield = 2 + $self->{'vertical'}; # width horiz, height vert
956 $row_width = 0;
957 foreach my $cellinfo (@{$self->{'cellinfo_list'}}) {
958 my $cell = $cellinfo->{'cell'};
959 if (! $cell->get('visible')) { next; }
960 $row_width += ($cell->get_size ($self,undef)) [$sizefield];
961 }
962 ### _row_width() calc: "$index is $row_width"
963 return ($row_widths->{$index} = $row_width);
964 }
965  
966 #------------------------------------------------------------------------------
967 # programmatic scrolling
968  
969 sub scroll_to_start {
970 my ($self) = @_;
971 _scroll_to_pos ($self, 0, 0);
972 }
973  
974 sub scroll_pixels {
975 my ($self, $pixels) = @_;
976 _scroll_to_pos ($self, $self->{'want_x'} - $pixels, $self->{'want_index'});
977 }
978  
979 sub _scroll_to_pos {
980 my ($self, $x, $index) = @_;
981 #### _scroll_to_pos(): "x=$x index=$index"
982  
983 $self->{'want_index'} = $index;
984 $self->{'want_x'} = $x;
985  
986 # If drawable(), ie. GTK_WIDGET_DRAWABLE(), is true, meaning widget
987 # show()ed and window mapped, then draw after a server sync. If unmapped
988 # then programmatic scrolls just move the position around and the eventual
989 # map will get an expose to draw.
990 #
991 if ($self->drawable) {
992 $self->{'sync_call'} ||= do {
993 my $weak_self = $self;
994 Scalar::Util::weaken ($weak_self);
995 Gtk2::Ex::SyncCall->sync ($self, \&_sync_call_handler, \$weak_self);
996 };
997 }
998 }
999 sub _sync_call_handler {
1000 my ($ref_weak_self) = @_;
1001 my $self = $$ref_weak_self || return;
1002 #### TickerView _sync_call_handler()
1003  
1004 $self->{'sync_call'} = undef;
1005  
1006 # Recheck drawable(), GTK_WIDGET_DRAWABLE(), in case unmapped in between
1007 # the last scroll and the server sync reply. If still mapped then do an
1008 # immediate draw via queue_draw and forced update.
1009 #
1010 # process_updates() normally runs under an idle at GDK_PRIORITY_REDRAW,
1011 # but don't wait to get down there. Currently at GDK_PRIORITY_EVENTS from
1012 # the sync and the sync means now is a good time for a forced draw.
1013 #
1014 if ($self->drawable) {
1015 $self->queue_draw;
1016 $self->window->process_updates (1);
1017 }
1018 }
1019  
1020  
1021 #------------------------------------------------------------------------------
1022 # drawing style changes
1023  
1024 # 'direction_changed' class closure
1025 sub _do_direction_changed {
1026 my ($self, $prev_dir) = @_;
1027 _pixmap_queue_draw ($self);
1028  
1029 # As of Gtk 2.18 the GtkWidget code in gtk_widget_real_direction_changed()
1030 # (previously called gtk_widget_direction_changed()) does a queue_resize(),
1031 # which is neither needed or wanted here. But a direction change should
1032 # be infrequent and better make sure anything GtkWidget does in the future
1033 # gets run.
1034 $self->signal_chain_from_overridden ($prev_dir);
1035 }
1036  
1037 # 'notify' class closure
1038 # SET_PROPERTY() is called only for own class properties, this default
1039 # handler sees changes to those defined by the GtkWidget superclass (and all
1040 # other sub and super classes)
1041 sub _do_notify {
1042 my ($self, $pspec) = @_;
1043 my $pname = $pspec->get_name;
1044 ### TickerView _do_notify(): $pname
1045  
1046 if ($pname eq 'sensitive') {
1047 # gtk_widget_set_sensitive does $self->queue_draw, so just need to
1048 # invalidate pixmap contents here for a redraw
1049 ### redraw
1050 _pixmap_queue_draw ($self);
1051 }
1052 $self->signal_chain_from_overridden ($pspec);
1053 }
1054  
1055 # 'state_changed' class closure ($self, $state)
1056 # 'style_set' class closure ($self, $prev_style)
1057 sub _do_state_or_style_changed {
1058 my ($self, $arg) = @_;
1059 if (DEBUG) { print "TickerView state-changed or style-set '",
1060 (defined $arg ? $arg : 'undef'),"'\n"; }
1061 _pixmap_queue_draw ($self);
1062 $self->signal_chain_from_overridden ($arg);
1063 }
1064  
1065  
1066 #------------------------------------------------------------------------------
1067 # scroll timer
1068 #
1069 # _update_timer() starts or stops the timer according to the numerous
1070 # conditions set out in that func. In general the idea is not to run the
1071 # timer when there's nothing to see and/or move: eg. the window is not
1072 # visible, or there's nothing in the model+renderers. Care must be taken to
1073 # call _update_timer() when any of the conditions may have changed.
1074 #
1075 # The timer action itself is pretty simple, it just calls the public
1076 # $self->scroll_pixels() to make the move, by an amount based on elapsed
1077 # real time, per "OTHER NOTES" in the pod below. The hairy stuff in
1078 # scroll_pixels() collapsing multiple motions and drawing works just as well
1079 # from the timer as it does from application uses of that func. In fact the
1080 # collapsing exists mainly to help if the timer runs a touch too fast for
1081 # the server's drawing.
1082 #
1083  
1084 # _TIMER_PRIORITY is below the drawing priority GDK_PRIORITY_EVENTS in
1085 # _sync_call_handler(), so drawing of the current position goes out before
1086 # making a scroll to a new position.
1087 #
1088 # Try _TIMER_PRIORITY below GDK_PRIORITY_REDRAW too, to hopefully cooperate
1089 # with redrawing of other widgets, letting their drawing go out before
1090 # scrolling the ticker.
1091 #
1092 use constant _TIMER_PRIORITY => (GDK_PRIORITY_REDRAW + 10);
1093  
1094 # _gettime() returns a floating point count of seconds since some fixed but
1095 # unspecified origin time.
1096 #
1097 # clock_gettime(CLOCK_REALTIME) is preferred. clock_gettime() always
1098 # exists, but it croaks if there's no such C library func. In that case
1099 # fall back on the hires time(), which is whatever best thing Time::HiRes
1100 # can do, probably gettimeofday() normally.
1101 #
1102 # Maybe it'd be worth checking clock_getres() to see it's a decent
1103 # resolution. It's conceivable some old implementations might do
1104 # CLOCK_REALTIME just from the CLK_TCK times() counter, giving only 10
1105 # millisecond resolution. That's enough for a modest 10 or 20 frames/sec,
1106 # but if attempting say 100 frames on a fast computer for ultra smoothness
1107 # then higher resolution would be needed.
1108 #
1109 sub _gettime {
1110 return Time::HiRes::clock_gettime (Time::HiRes::CLOCK_REALTIME());
1111 }
1112 unless (eval { _gettime(); 1 }) {
1113 ### TickerView fallback to Time HiRes time() due to clock_gettime() error: $@
1114 no warnings;
1115 *_gettime = \&Time::HiRes::time;
1116 }
1117  
1118 # start or stop the scroll timer according to the various settings
1119 sub _update_timer {
1120 my ($self) = @_;
1121  
1122 my $want_timer = $self->{'run'}
1123 && ! $self->{'paused_count'}
1124 && $self->mapped
1125 && $self->{'visibility_state'} ne 'fully-obscured'
1126 && $self->{'cellinfo_list'}
1127 && @{$self->{'cellinfo_list'}} # renderer list not empty
1128 && $self->{'frame_rate'} > 0
1129 && ! defined $self->{'drag_xy'} # not in a drag
1130 && $self->{'model'}
1131 && ! $self->{'model_empty'};
1132  
1133 if (DEBUG) {
1134 print " _update_timer run=", $self->{'run'},
1135 " paused=", ($self->{'paused_count'}||'no'),
1136 " mapped=", $self->mapped ? 1 : 0,
1137 " visibility=", $self->{'visibility_state'},
1138 " model=", ($self->{'model'} ? 'yes' : 'none'),
1139 " model_empty=", $self->{'model_empty'} || '0',
1140 " (iter_first=", (! defined $self->{'model'} ? 'n/a)'
1141 : $self->{'model'}->get_iter_first ? 'yes)' : 'no)'),
1142 " --> want ", ($want_timer ? 'yes' : 'no'), "\n";
1143 }
1144  
1145 $self->{'timer'} = $want_timer &&
1146 ($self->{'timer'} # existing timer if already running
1147 || do { # otherwise a new one
1148 my $period = POSIX::ceil (1000.0 / $self->{'frame_rate'});
1149 if (DEBUG) { print "TickerView start timer, $period ms\n"; }
1150
1151 my $weak_self = $self;
1152 Scalar::Util::weaken ($weak_self);
1153 $self->{'prev_time'} = _gettime();
1154 require Glib::Ex::SourceIds;
1155 Glib::Ex::SourceIds->new
1156 (Glib::Timeout->add ($period, \&_do_timer, \$weak_self,
1157 _TIMER_PRIORITY));
1158 });
1159 }
1160  
1161 sub _do_timer {
1162 my ($ref_weak_self) = @_;
1163 # shouldn't see an undef in $$ref_weak_self because the timer should be
1164 # stopped already by _do_unrealize in the course of widget destruction,
1165 # but if for some reason that hasn't happened then stop it now
1166 my $self = $$ref_weak_self || return 0; # Glib::SOURCE_REMOVE
1167  
1168 my $t = _gettime();
1169 my $delta = $t - $self->{'prev_time'};
1170 $self->{'prev_time'} = $t;
1171  
1172 # Watch out for the clock going backwards, don't want to scroll back.
1173 # Watch out for jumping wildly forwards too due to the process blocked for
1174 # a while, don't want to churn through some massive pixel count forwards.
1175 $delta = min (5, max (0, $delta));
1176  
1177 my $step = $self->{'speed'} * $delta;
1178 $self->scroll_pixels ($step);
1179 if (DEBUG >= 2) { print "_do_timer scroll $delta seconds, $step pixels,",
1180 " to $self->{'want_x'}\n"; }
1181 return 1; # Glib::SOURCE_CONTINUE
1182 }
1183  
1184 # 'map' class closure ($self)
1185 # 'unmap' class closure ($self)
1186 #
1187 # This is asking the widget to map or unmap itself, not map-event or
1188 # unmap-event back from the server.
1189 #
1190 sub _do_map_or_unmap {
1191 my ($self) = @_;
1192 ### TickerView _do_map_or_unmap()
1193  
1194 # chain before _update_timer(), so the GtkWidget code sets or unsets the
1195 # mapped flag which _update_timer() will look at
1196 $self->signal_chain_from_overridden;
1197 _update_timer ($self);
1198 }
1199  
1200 # 'unrealize' class closure
1201 # (asking the widget to unrealize itself)
1202 #
1203 # When a ticker is removed from a container only unrealize is called, not
1204 # unmap then unrealize, hence an _update_timer() check here as well as
1205 # _do_map_or_unmap() above.
1206 #
1207 sub _do_unrealize {
1208 my ($self) = @_;
1209 ### TickerView _do_unrealize()
1210  
1211 # chain before _update_timer(), so the GtkWidget code clears the mapped flag
1212 $self->signal_chain_from_overridden;
1213  
1214 @{$self->{'drawn_array'}} = (); # full redraw if realized again later
1215 $self->{'pixmap'} = undef; # possible different depth if realized again later
1216 _update_timer ($self);
1217 }
1218  
1219 # 'visibility_notify_event' class closure
1220 sub _do_visibility_notify_event {
1221 my ($self, $event) = @_;
1222 ### TickerView _do_visibility_notify_event(): $event->state
1223 $self->{'visibility_state'} = $event->state;
1224 _update_timer ($self);
1225 return $self->signal_chain_from_overridden ($event);
1226 }
1227  
1228  
1229 #------------------------------------------------------------------------------
1230 # dragging
1231 #
1232 # The basic operation here is pretty simple, it's just a matter of calling
1233 # the public $self->scroll_pixels() with each mouse move amount as reported
1234 # by motion-notify. The hairy stuff in scroll_pixels() to collapse moving
1235 # and drawing works just as well for moves here as for application calls.
1236 #
1237 # If someone does a grab_pointer, either within the program or another
1238 # client, then we'll no longer get motion notifies. Should timer based
1239 # scrolling resume immediately, or only on button release? If the new grab
1240 # is some unrelated action taking over then immediately might be best. But
1241 # only on button release may be more consistent, in having the timer
1242 # scrolling resume only on button release. The latter is done for now.
1243 #
1244 # If the window is moved during the drag, either repositioned by application
1245 # code, or repositioned by the window manager etc, then it's possible to
1246 # either
1247 #
1248 # 1. Let the displayed contents stay with the left edge of the window.
1249 # 2. Let the displayed contents stay with the mouse, so it's like the
1250 # window move reveals a different portion.
1251 #
1252 # Neither is too difficult, but 1 is adopted since in 2 there's a bit of
1253 # flashing when the server copies the contents with the move and they then
1254 # have to be redrawn. (Redrawn under size-allocate, since there's only
1255 # configure-notify for a window move, no mouse motion-notify event.)
1256 #
1257 # Perhaps the double-buffering extension could help with the flashing, but
1258 # it'd have to be applied to the parent window, and could only work when the
1259 # move originates client-side, not say from the window manager. For now 1
1260 # is easier, and window moves during a drag should be fairly unusual anyway.
1261 #
1262 # To implement 1 the mouse position for dragging is maintained in root
1263 # window coordinates. This means it's independent of the ticker window
1264 # position. On that basis don't need to pay any attention to the window
1265 # position, simply apply root window based mouse motion to scroll_pixels().
1266 # Both x and y are maintained so that you can actually change the
1267 # "orientation" property in the middle of a drag and still get the right
1268 # result!
1269 #
1270  
1271 # if (0) {
1272 # my $bindings = Gtk2::BindingSet->new ('Gtk2__Ex__TickerView');
1273 # $bindings->entry_add_signal
1274 # (Gtk2::Gdk->keyval_from_name('Pointer_Button1'),[],
1275 # 'start-drag');
1276 # $bindings->entry_add_signal
1277 # (Gtk2::Gdk->keyval_from_name('Pointer_Button1'),['release-mask'],
1278 # 'end-drag');
1279 # # priority level "gtk" treating this as widget level default, for
1280 # # overriding by application or user RC
1281 # $bindings->add_path ('class', 'Gtk2__Ex__TickerView', 'gtk');
1282 # }
1283  
1284 sub is_drag_active {
1285 my ($self) = @_;
1286 return (defined $self->{'drag_xy'});
1287 }
1288  
1289 # 'button_press_event' class closure, getting Gtk2::Gdk::Event::Button
1290 sub _do_button_press_event {
1291 my ($self, $event) = @_;
1292 #### TickerView button_press: $event->button
1293 if ($event->button == 1) {
1294 $self->{'drag_xy'} = [ $event->root_coords ];
1295 _update_timer ($self); # stop timer
1296 }
1297 return $self->signal_chain_from_overridden ($event);
1298 }
1299  
1300 # 'motion_notify_event' class closure, getting Gtk2::Gdk::Event::Motion
1301 #
1302 # Use of is_hint() supports 'pointer-motion-hint-mask' perhaps set by the
1303 # application or some add-on feature. Dragging only runs from a mouse
1304 # button so for now it's enough to use get_pointer() rather than
1305 # $display->get_state().
1306 #
1307 sub _do_motion_notify_event {
1308 my ($self, $event) = @_;
1309 #### TickerView _do_motion_notify_event()
1310 if (defined $self->{'drag_xy'}) { # ignore motion/drags of other buttons
1311 _drag_scroll ($self, $event);
1312 }
1313 return $self->signal_chain_from_overridden ($event);
1314 }
1315  
1316 # 'button_release_event' class closure, getting Gtk2::Gdk::Event::Button
1317 #
1318 sub _do_button_release_event {
1319 my ($self, $event) = @_;
1320 #### TickerView _do_button_release_event(): $event->button
1321  
1322 if (defined $self->{'drag_xy'} && $event->button == 1) {
1323 _drag_scroll ($self, $event); # final dragged position from this event
1324 delete $self->{'drag_xy'};
1325 _update_timer ($self); # restart timer
1326 }
1327 return $self->signal_chain_from_overridden ($event);
1328 }
1329  
1330 # $event is either Gtk2::Gdk::Event::Motion or Gtk2::Gdk::Event::Button
1331 sub _drag_scroll {
1332 my ($self, $event) = @_;
1333 if (DEBUG >= 2) { print " _drag_scroll ",
1334 ($event->can('is_hint') && $event->is_hint
1335 ? 'hint' : 'not-hint'), "\n"; }
1336  
1337 my @xy = ($event->can('is_hint') && $event->is_hint
1338 ? $self->get_root_window->get_pointer
1339 : $event->root_coords);
1340  
1341 # step is simply how much the new position has moved from the old one
1342 my $i = $self->{'vertical'};
1343 my $step = $self->{'drag_xy'}->[$i] - $xy[$i];
1344 @{$self->{'drag_xy'}} = @xy;
1345  
1346 if ($self->get_direction eq 'rtl') { $step = -$step; }
1347 if (DEBUG >= 2) { print " step $step\n"; }
1348 $self->scroll_pixels ($step);
1349 }
1350  
1351 #------------------------------------------------------------------------------
1352 # mouse wheel scroll
1353  
1354 my %direction_sign = (up => -1,
1355 down => 1,
1356 left => -1,
1357 right => 1);
1358 my %direction_is_vertical = (up => 1,
1359 down => 1,
1360 left => 0,
1361 right => 0);
1362 # 'scroll-event' class closure, getting Gtk2::Gdk::Event::Scroll
1363 sub _do_scroll_event {
1364 my ($self, $event) = @_;
1365 #### TickerView scroll-event: $event->direction
1366 my $dir = $event->direction;
1367 my $vertical = $self->{'vertical'};
1368  
1369 # width when horiz, height when vert
1370 my $step = ($self->allocation->values)[2 + $vertical]
1371 * ($event->state & 'control-mask' ? 0.9 : 0.1)
1372 * $direction_sign{$dir};
1373 unless ($direction_is_vertical{$dir} ^ $vertical) {
1374 if ($self->get_direction eq 'rtl') { $step = - $step; }
1375 }
1376 $self->scroll_pixels ($step);
1377 return $self->signal_chain_from_overridden ($event);
1378 }
1379  
1380 #------------------------------------------------------------------------------
1381 # renderer changes
1382  
1383 sub _cellinfo_list_changed {
1384 my ($self) = @_;
1385 ### TickerView _cellinfo_list_changed()
1386 %{$self->{'row_widths'}} = ();
1387 _pixmap_queue_draw ($self);
1388 _update_timer ($self); # possible newly empty or non-empty cellinfo list
1389 $self->SUPER::_cellinfo_list_changed;
1390 }
1391  
1392 sub _cellinfo_attributes_changed {
1393 my ($self) = @_;
1394 ### TickerView _cellinfo_attributes_changed()
1395 %{$self->{'row_widths'}} = ();
1396 _pixmap_queue_draw ($self);
1397 $self->SUPER::_cellinfo_attributes_changed;
1398 }
1399  
1400  
1401 #------------------------------------------------------------------------------
1402 # model changes
1403 #
1404 # The main optimization attempted here is to do nothing when changed rows
1405 # are off-screen, or rather off-pixmap, with the aim of doing no drawing
1406 # when undisplayed parts of the model change.
1407 #
1408 # In practice you have to be in fixed-height-mode for off-screen updates to
1409 # do nothing at all since in the default "all rows sized" mode any change or
1410 # insert or delete has to re-examine all rows. The insert could check only
1411 # for an increase, but doesn't do that currently.
1412 #
1413  
1414 # 'row-changed' on the model
1415 sub _do_row_changed {
1416 my ($model, $path, $iter, $ref_weak_self) = @_;
1417 my $self = $$ref_weak_self || return;
1418 ### _do_row_changed() path: $path->to_string
1419 $path->get_depth == 1 || return; # only top rows of the model
1420 my ($index) = $path->get_indices;
1421  
1422 # recalculate width
1423 delete $self->{'row_widths'}->{$index};
1424  
1425 # fixed-height-mode means every row is the same height so a change to any
1426 # one of them doesn't affect the previously calculated size -- even when
1427 # it's a change to the representative row 0. Believe that's how
1428 # GtkTreeView interprets its fixed-height-mode, and it has the happy
1429 # effect of not provoking repeated rechecks if row 0 changes a lot.
1430 #
1431 # In non fixed-height-mode, however, every row change potentially
1432 # increases or decreases the height. (Or at least a change to the highest
1433 # could decrease, or a change to any of the equal highest could increase.)
1434 #
1435 if (! $self->{'fixed_height_mode'}) {
1436 $self->queue_resize;
1437 }
1438  
1439 # if changed row is in pixmap then redraw
1440 _pixmap_queue_draw_if_index ($self, $index);
1441 }
1442  
1443 # 'row-inserted' on the model
1444 sub _do_row_inserted {
1445 my ($model, $path, $iter, $ref_weak_self) = @_;
1446 my $self = $$ref_weak_self || return;
1447 ### _do_row_inserted() path: $path->to_string
1448 $path->get_depth == 1 || return; # only top rows
1449 my ($index) = $path->get_indices;
1450  
1451 if ($self->{'model_empty'}) {
1452 # empty -> non-empty restarts timer if stopped due to empty
1453 _update_timer ($self);
1454 }
1455 if ($self->{'model_empty'} || ! $self->{'fixed_height_mode'}) {
1456 # empty -> non-empty changes size from zero to something;
1457 # and any new row insertion resizes when non fixed-height-mode
1458 # (could just see if this new row bigger than already calculated)
1459 $self->queue_resize;
1460 }
1461 $self->{'model_empty'} = 0;
1462  
1463 _pixmap_queue_draw_if_index ($self, $index);
1464 _apply_remap ($self,
1465 # called as $new_index = $remap->($old_index)
1466 sub { $_[0] >= $index ? $_[0] + 1 : $_[0] });
1467 }
1468  
1469 # 'row-deleted' on the model
1470 sub _do_row_deleted {
1471 my ($model, $path, $ref_weak_self) = @_;
1472 my $self = $$ref_weak_self || return;
1473 ### _do_row_deleted() path: $path->to_string
1474 $path->get_depth == 1 || return; # only top rows
1475 my ($index) = $path->get_indices;
1476  
1477 delete $self->{'row_widths'}->{$index};
1478  
1479 my $model_empty = $self->{'model_empty'} = ! $model->get_iter_first;
1480 if ($model_empty) {
1481 # becoming empty, stop timer while empty
1482 _update_timer ($self);
1483 }
1484 if ($model_empty || ! $self->{'fixed_height_mode'}) {
1485 # becoming empty will become zero size;
1486 # or if ever row checked then any delete affects height
1487 # (actually only a delete of the highest row affects it, if wanted to
1488 # record which was the biggest)
1489 $self->queue_resize;
1490 }
1491  
1492 # want_index and row_widths move down.
1493 # If want_index itself is deleted then leave it unchanged to show from the
1494 # next following, and if it was the last row then it'll wrap around in the
1495 # draw.
1496 #
1497 _pixmap_queue_draw_if_index ($self, $index);
1498 _apply_remap ($self,
1499 # called as $new_index = $remap->($old_index)
1500 sub { $_[0] > $index ? $_[0] - 1 : $_[0] });
1501 }
1502  
1503 # 'rows-reordered' signal on the model
1504 sub _do_rows_reordered {
1505 my ($model, $reordered_path, $reordered_iter, $aref, $ref_weak_self) = @_;
1506 my $self = $$ref_weak_self || return;
1507 ### _do_rows_reordered()
1508 if (defined $reordered_iter) { return; } # top rows only
1509  
1510 # $oldpos == $aref->[$newpos], ie. aref says where the row used to be.
1511 # $remap{$oldpos} == $newpos, ie. where the old has been sent
1512 # Building a hash might be a bit unnecessary if not much to remap, but
1513 # it's less code than a linear search or similar.
1514 #
1515 my %remap;
1516 @remap{@$aref} = (0 .. $#$aref);
1517 if (DEBUG) { require Data::Dumper;
1518 print " remap ",
1519 Data::Dumper->new([\%remap],['remap'])->Sortkeys(1)->Dump; }
1520 # want_index and row_widths permute
1521 # allow for indexes out of range in case want_index yet unnormalized
1522 # called as $new_index = $remap->($old_index)
1523 my $remap = sub { defined $remap{$_[0]} ? $remap{$_[0]} : $_[0] };
1524  
1525 # Set the pixmap to redraw if the drawn rows are no longer a contiguous
1526 # run, modulo the model length. This is a bit of work to check, but the
1527 # pixmap contents can be retained nicely under rotations or shuffle ups or
1528 # downs that don't affect the displayed portion.
1529 my $len = scalar @$aref;
1530 my $delta_func = sub { ($_[0] - $remap->($_[0]) + $len) % $len };
1531 my $drawn = $self->{'drawn_array'};
1532 if (@$drawn) {
1533 my $want_delta = $delta_func->($drawn->[0]);
1534 for (my $i = 2; $i < @$drawn; $i += 2) {
1535 if ($delta_func->($drawn->[$i]) != $want_delta) {
1536 _pixmap_queue_draw ($self); # shuffled about, must redraw
1537 last;
1538 }
1539 }
1540 }
1541 _apply_remap ($self, $remap);
1542 }
1543  
1544 # set the pixmap to redraw if $index is drawn in it
1545 sub _pixmap_queue_draw_if_index {
1546 my ($self, $index) = @_;
1547 my $drawn = $self->{'drawn_array'};
1548 for (my $i = 0; $i < @$drawn; $i += 2) {
1549 if ($drawn->[$i] == $index) {
1550 _pixmap_queue_draw ($self);
1551 return 1;
1552 }
1553 }
1554 return 0;
1555 }
1556  
1557 # Remap indexes in want_index, drawn_array, and row_widths. drawn_array is
1558 # empty at this point if it's going to be redrawn
1559 sub _apply_remap {
1560 my ($self, $remap) = @_;
1561 ### _apply_remap(): $remap
1562  
1563 if (defined (my $want_index = $self->{'want_index'})) {
1564 if (DEBUG) { print " want_index $want_index to ",
1565 $remap->($want_index),"\n"; }
1566 $self->{'want_index'} = $remap->($want_index);
1567 }
1568 my $drawn = $self->{'drawn_array'};
1569 if (@$drawn) {
1570 for (my $i = 0; $i < @$drawn; $i += 2) {
1571 $drawn->[$i] = $remap->($drawn->[$i]);
1572 }
1573 }
1574 _hash_keys_remap ($self->{'row_widths'}, $remap);
1575 }
1576  
1577 # modify the keys in %$href by $newkey = $func->($oldkey)
1578 # the value associated with $oldkey moves to $newkey
1579 #
1580 sub _hash_keys_remap {
1581 my ($href, $func) = @_;
1582 %$href = map { ($func->($_), $href->{$_}) } keys %$href;
1583 }
1584  
1585  
1586 #------------------------------------------------------------------------------
1587 # generic helpers
1588  
1589 # _make_all_zeros_proc() returns a procedure to be called
1590 # $func->($index,$width) designed to protect against every $index having a
1591 # zero $width.
1592 #
1593 # $func returns true until it sees an $index==0 and then a second $index==0,
1594 # with all calls having $width==0. The idea is that if the drawing,
1595 # scrolling or whatever loop has gone from $index zero all the way up and
1596 # around back to $index zero again, and all the $width's seen are zero, then
1597 # it should bail out.
1598 #
1599 # Any non-zero $width seen makes the returned procedure always return true.
1600 # It might be only a single index position out of thousands, but that's
1601 # enough.
1602 #
1603 sub _make_all_zeros_proc {
1604 my $seen_nonzero = 0;
1605 my $count_index_zero = 0;
1606 return sub {
1607 my ($index, $width) = @_;
1608 if ($width != 0) { $seen_nonzero = 1; }
1609 if ($index == 0) { $count_index_zero++; }
1610 return (! $seen_nonzero) && ($count_index_zero >= 2);
1611 }
1612 }
1613  
1614  
1615 #------------------------------------------------------------------------------
1616 # other method funcs
1617  
1618 sub get_path_at_pos {
1619 my ($self, $x, $y) = @_;
1620 ### get_path_at_pos(): "$x,$y"
1621  
1622 # Go from the want_x/want_index desired position, even if the drawing
1623 # isn't yet actually displaying that. This makes most sense after a
1624 # programmatic scroll, and if it's a user button press then the display
1625 # will only be a moment away from showing that want_x/want_index position.
1626 #
1627 my $index = $self->{'want_index'};
1628 $x -= $self->{'want_x'};
1629 if (DEBUG) { print " adj for want_x=",$self->{'want_x'},", to x=$x\n"; }
1630  
1631 ($x, $index) = _normalize ($self, -$x, $index);
1632 if (DEBUG) { print " got ", (defined $x ? $x : 'undef'),
1633 ",",(defined $index ? $index : 'undef'),"\n"; }
1634 if (defined $x) {
1635 return Gtk2::TreePath->new_from_indices ($index);
1636 } else {
1637 return undef;
1638 }
1639 }
1640  
1641 1;
1642 __END__
↑ Summary