hotfix negative TC editing - problem was introduced in r13491
[ardour.git] / gtk2_ardour / audio_clock.cc
1 /*
2     Copyright (C) 1999 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <cstdio> // for sprintf
21 #include <cmath>
22
23 #include "pbd/convert.h"
24 #include "pbd/enumwriter.h"
25
26 #include <gtkmm/style.h>
27 #include <sigc++/bind.h>
28
29 #include "gtkmm2ext/cairocell.h"
30 #include "gtkmm2ext/utils.h"
31 #include "gtkmm2ext/rgb_macros.h"
32
33 #include "ardour/profile.h"
34 #include "ardour/session.h"
35 #include "ardour/slave.h"
36 #include "ardour/tempo.h"
37 #include "ardour/types.h"
38
39 #include "ardour_ui.h"
40 #include "audio_clock.h"
41 #include "global_signals.h"
42 #include "utils.h"
43 #include "keyboard.h"
44 #include "gui_thread.h"
45 #include "i18n.h"
46
47 using namespace ARDOUR;
48 using namespace PBD;
49 using namespace Gtk;
50 using namespace std;
51
52 using Gtkmm2ext::Keyboard;
53
54 sigc::signal<void> AudioClock::ModeChanged;
55 vector<AudioClock*> AudioClock::clocks;
56 const double AudioClock::info_font_scale_factor = 0.5;
57 const double AudioClock::separator_height = 0.0;
58 const double AudioClock::x_leading_padding = 6.0;
59
60 #define BBT_BAR_CHAR "|"
61 #define BBT_SCANF_FORMAT "%" PRIu32 "%*c%" PRIu32 "%*c%" PRIu32
62 #define INFO_FONT_SIZE ((int)round(font_size * info_font_scale_factor))
63
64 AudioClock::AudioClock (const string& clock_name, bool transient, const string& widget_name,
65                         bool allow_edit, bool follows_playhead, bool duration, bool with_info)
66         : ops_menu (0)
67         , _name (clock_name)
68         , is_transient (transient)
69         , is_duration (duration)
70         , editable (allow_edit)
71         , _follows_playhead (follows_playhead)
72         , _off (false)
73         , _fixed_width (true)
74         , layout_x_offset (0)
75         , em_width (0)
76         , _edit_by_click_field (false)
77         , _negative_allowed (false)
78         , edit_is_negative (false)
79         , editing_attr (0)
80         , foreground_attr (0)
81         , first_height (0)
82         , first_width (0)
83         , layout_height (0)
84         , layout_width (0)
85         , info_height (0)
86         , upper_height (0)
87         , mode_based_info_ratio (1.0)
88         , corner_radius (9)
89         , font_size (10240)
90         , editing (false)
91         , bbt_reference_time (-1)
92         , last_when(0)
93         , last_pdelta (0)
94         , last_sdelta (0)
95         , dragging (false)
96         , drag_field (Field (0))
97
98 {
99         set_flags (CAN_FOCUS);
100
101         _layout = Pango::Layout::create (get_pango_context());
102         _layout->set_attributes (normal_attributes);
103
104         if (with_info) {
105                 _left_layout = Pango::Layout::create (get_pango_context());
106                 _right_layout = Pango::Layout::create (get_pango_context());
107         }
108
109         set_widget_name (widget_name);
110
111         _mode = BBT; /* lie to force mode switch */
112         set_mode (Timecode);
113         set (last_when, true);
114
115         if (!is_transient) {
116                 clocks.push_back (this);
117         }
118
119         ColorsChanged.connect (sigc::mem_fun (*this, &AudioClock::set_colors));
120         DPIReset.connect (sigc::mem_fun (*this, &AudioClock::dpi_reset));
121 }
122
123 AudioClock::~AudioClock ()
124 {
125         delete foreground_attr;
126         delete editing_attr;
127 }
128
129 void
130 AudioClock::set_widget_name (const string& str)
131 {
132         if (str.empty()) {
133                 set_name ("clock");
134         } else {
135                 set_name (str + " clock");
136         }
137
138         if (is_realized()) {
139                 set_colors ();
140         }
141 }
142
143
144 void
145 AudioClock::on_realize ()
146 {
147         CairoWidget::on_realize ();
148         set_font ();
149         set_colors ();
150 }
151
152 void
153 AudioClock::set_font ()
154 {
155         Glib::RefPtr<Gtk::Style> style = get_style ();
156         Pango::FontDescription font;
157         Pango::AttrFontDesc* font_attr;
158
159         if (!is_realized()) {
160                 font = get_font_for_style (get_name());
161         } else {
162                 font = style->get_font();
163         }
164
165         font_size = font.get_size();
166
167         font_attr = new Pango::AttrFontDesc (Pango::Attribute::create_attr_font_desc (font));
168
169         normal_attributes.change (*font_attr);
170         editing_attributes.change (*font_attr);
171
172         /* now a smaller version of the same font */
173
174         delete font_attr;
175         font.set_size ((int) lrint (font_size * info_font_scale_factor));
176         font.set_weight (Pango::WEIGHT_NORMAL);
177         font_attr = new Pango::AttrFontDesc (Pango::Attribute::create_attr_font_desc (font));
178
179         info_attributes.change (*font_attr);
180
181         /* and an even smaller one */
182
183         delete font_attr;
184
185         /* get the figure width for the font. This doesn't have to super
186          * accurate since we only use it to measure the (roughly 1 character)
187          * offset from the position Pango tells us for the "cursor"
188          */
189
190         Glib::RefPtr<Pango::Layout> tmp = Pango::Layout::create (get_pango_context());
191         int ignore_height;
192
193         tmp->set_text ("8");
194         tmp->get_pixel_size (em_width, ignore_height);
195
196         /* force redraw of markup with new font-size */
197         set (last_when, true);
198 }
199
200 void
201 AudioClock::set_active_state (Gtkmm2ext::ActiveState s)
202 {
203         CairoWidget::set_active_state (s);
204         set_colors ();
205 }
206
207 void
208 AudioClock::set_colors ()
209 {
210         int r, g, b, a;
211
212         uint32_t bg_color;
213         uint32_t text_color;
214         uint32_t editing_color;
215         uint32_t cursor_color;
216
217         if (active_state()) {
218                 bg_color = ARDOUR_UI::config()->color_by_name (string_compose ("%1 active: background", get_name()));
219                 text_color = ARDOUR_UI::config()->color_by_name (string_compose ("%1 active: text", get_name()));
220                 editing_color = ARDOUR_UI::config()->color_by_name (string_compose ("%1 active: edited text", get_name()));
221                 cursor_color = ARDOUR_UI::config()->color_by_name (string_compose ("%1 active: cursor", get_name()));
222         } else {
223                 bg_color = ARDOUR_UI::config()->color_by_name (string_compose ("%1: background", get_name()));
224                 text_color = ARDOUR_UI::config()->color_by_name (string_compose ("%1: text", get_name()));
225                 editing_color = ARDOUR_UI::config()->color_by_name (string_compose ("%1: edited text", get_name()));
226                 cursor_color = ARDOUR_UI::config()->color_by_name (string_compose ("%1: cursor", get_name()));
227         }
228
229         /* store for bg and cursor in render() */
230
231         UINT_TO_RGBA (bg_color, &r, &g, &b, &a);
232
233         bg_r = r/255.0;
234         bg_g = g/255.0;
235         bg_b = b/255.0;
236         bg_a = a/255.0;
237
238         UINT_TO_RGBA (cursor_color, &r, &g, &b, &a);
239
240         cursor_r = r/255.0;
241         cursor_g = g/255.0;
242         cursor_b = b/255.0;
243         cursor_a = a/255.0;
244
245         /* rescale for Pango colors ... sigh */
246
247         r = lrint (r * 65535.0);
248         g = lrint (g * 65535.0);
249         b = lrint (b * 65535.0);
250
251         UINT_TO_RGBA (text_color, &r, &g, &b, &a);
252         r = lrint ((r/255.0) * 65535.0);
253         g = lrint ((g/255.0) * 65535.0);
254         b = lrint ((b/255.0) * 65535.0);
255         foreground_attr = new Pango::AttrColor (Pango::Attribute::create_attr_foreground (r, g, b));
256
257         UINT_TO_RGBA (editing_color, &r, &g, &b, &a);
258         r = lrint ((r/255.0) * 65535.0);
259         g = lrint ((g/255.0) * 65535.0);
260         b = lrint ((b/255.0) * 65535.0);
261         editing_attr = new Pango::AttrColor (Pango::Attribute::create_attr_foreground (r, g, b));
262
263         normal_attributes.change (*foreground_attr);
264         info_attributes.change (*foreground_attr);
265         editing_attributes.change (*foreground_attr);
266         editing_attributes.change (*editing_attr);
267
268         if (!editing) {
269                 _layout->set_attributes (normal_attributes);
270         } else {
271                 _layout->set_attributes (editing_attributes);
272         }
273
274         queue_draw ();
275 }
276
277 void
278 AudioClock::render (cairo_t* cr)
279 {
280         /* main layout: rounded rect, plus the text */
281
282         if (_need_bg) {
283                 cairo_set_source_rgba (cr, bg_r, bg_g, bg_b, bg_a);
284                 if (corner_radius) {
285                         if (_left_layout) {
286                                 Gtkmm2ext::rounded_top_half_rectangle (cr, 0, 0, get_width(), upper_height, corner_radius);
287                         } else {
288                                 Gtkmm2ext::rounded_rectangle (cr, 0, 0, get_width(), upper_height, corner_radius);
289                         }
290                 } else {
291                         cairo_rectangle (cr, 0, 0, get_width(), upper_height);
292                 }
293                 cairo_fill (cr);
294         }
295
296         if (!_fixed_width) {
297                 cairo_move_to (cr, layout_x_offset, 0);
298         } else {
299                 int xcenter = layout_x_offset > 0 ? 0 : (get_width() - _mode_width[_mode]) /2;
300                 cairo_move_to (cr, layout_x_offset + xcenter, (upper_height - layout_height) / 2.0);
301         }
302
303         pango_cairo_show_layout (cr, _layout->gobj());
304
305         if (_left_layout) {
306
307                 double h = get_height() - upper_height - separator_height;
308
309                 if (_need_bg) {
310                         cairo_set_source_rgba (cr, bg_r, bg_g, bg_b, bg_a);
311                 }
312
313                 if (mode_based_info_ratio != 1.0) {
314
315                         double left_rect_width = round (((get_width() - separator_height) * mode_based_info_ratio) + 0.5);
316
317                         if (_need_bg) {
318                                 if (corner_radius) {
319                                         Gtkmm2ext::rounded_bottom_half_rectangle (cr, 0, upper_height + separator_height,
320                                                         left_rect_width + (separator_height == 0 ? corner_radius : 0),
321                                                         h, corner_radius);
322                                 } else {
323                                         cairo_rectangle (cr, 0, upper_height + separator_height, left_rect_width, h);
324                                 }
325                                 cairo_fill (cr);
326                         }
327
328                         cairo_move_to (cr, x_leading_padding, upper_height + separator_height + ((h - info_height)/2.0));
329                         pango_cairo_show_layout (cr, _left_layout->gobj());
330
331                         if (_need_bg) {
332                                 if (corner_radius) {
333                                         Gtkmm2ext::rounded_bottom_half_rectangle (cr, left_rect_width + separator_height,
334                                                         upper_height + separator_height,
335                                                         get_width() - separator_height - left_rect_width,
336                                                         h, corner_radius);
337                                 } else {
338                                         cairo_rectangle (cr, left_rect_width + separator_height, upper_height + separator_height,
339                                                          get_width() - separator_height - left_rect_width, h);
340                                 }
341                                 cairo_fill (cr);
342                         }
343
344
345                         if (_right_layout->get_alignment() == Pango::ALIGN_RIGHT) {
346                                 /* right-align does not work per se beacuse layout width is unset.
347                                  * Using _right_layout->set_width([value >=0]) would also enable
348                                  * word-wrapping which is not wanted here.
349                                  * The solution is to custom align the layout depending on its size.
350                                  * if it is larger than the available space it will be cropped on the
351                                  * right edge rather than override text on the left side.
352                                  */
353                                 int x, rw, rh;
354                                 _right_layout->get_pixel_size(rw, rh);
355                                 x = get_width() - rw - separator_height - x_leading_padding;
356                                 if (x < x_leading_padding + left_rect_width + separator_height) {
357                                         /* rather cut off the right end than overlap with the text on the left */
358                                         x = x_leading_padding + left_rect_width + separator_height;
359                                 }
360                                 cairo_move_to (cr, x, upper_height + separator_height + ((h - info_height)/2.0));
361                         } else {
362                                 cairo_move_to (cr, x_leading_padding + left_rect_width + separator_height, upper_height + separator_height + ((h - info_height)/2.0));
363                         }
364                         pango_cairo_show_layout (cr, _right_layout->gobj());
365
366                 } else {
367                         /* no info to display, or just one */
368
369                         if (_need_bg) {
370                                 if (corner_radius) {
371                                         Gtkmm2ext::rounded_bottom_half_rectangle (cr, 0, upper_height + separator_height, get_width(), h, corner_radius);
372                                 } else {
373                                         cairo_rectangle (cr, 0, upper_height + separator_height, get_width(), h);
374                                 }
375                                 cairo_fill (cr);
376                         }
377                 }
378         }
379
380         if (editing) {
381                 if (!insert_map.empty()) {
382
383                         int xcenter = layout_x_offset > 0 ? 0 : (get_width() - _mode_width[_mode]) /2;
384
385                         if (input_string.length() < insert_map.size()) {
386                                 Pango::Rectangle cursor;
387
388                                 if (input_string.empty()) {
389                                         /* nothing entered yet, put cursor at the end
390                                            of string
391                                         */
392                                         cursor = _layout->get_cursor_strong_pos (edit_string.length() - 1);
393                                 } else {
394                                         cursor = _layout->get_cursor_strong_pos (insert_map[input_string.length()]);
395                                 }
396
397                                 cairo_set_source_rgba (cr, cursor_r, cursor_g, cursor_b, cursor_a);
398                                 if (!_fixed_width) {
399                                         cairo_rectangle (cr,
400                                                          min (get_width() - 2.0,
401                                                               (double) cursor.get_x()/PANGO_SCALE + layout_x_offset + xcenter + em_width), 0,
402                                                          2.0, cursor.get_height()/PANGO_SCALE);
403                                 } else {
404                                         cairo_rectangle (cr,
405                                                          min (get_width() - 2.0,
406                                                               (double) layout_x_offset + xcenter + cursor.get_x()/PANGO_SCALE + em_width),
407                                                          (upper_height - layout_height)/2.0,
408                                                          2.0, cursor.get_height()/PANGO_SCALE);
409                                 }
410                                 cairo_fill (cr);
411                         } else {
412                                 /* we've entered all possible digits, no cursor */
413                         }
414
415                 } else {
416                         if (input_string.empty()) {
417                                 cairo_set_source_rgba (cr, cursor_r, cursor_g, cursor_b, cursor_a);
418                                 if (!_fixed_width) {
419                                         cairo_rectangle (cr,
420                                                          (get_width()/2.0),
421                                                          0,
422                                                          2.0, upper_height);
423                                 } else {
424                                         cairo_rectangle (cr,
425                                                          (get_width()/2.0),
426                                                          (upper_height - layout_height)/2.0,
427                                                          2.0, upper_height);
428                                 }
429                                 cairo_fill (cr);
430                         }
431                 }
432         }
433 }
434
435 void
436 AudioClock::on_size_allocate (Gtk::Allocation& alloc)
437 {
438         CairoWidget::on_size_allocate (alloc);
439
440         if (_left_layout) {
441                 upper_height = (get_height()/2.0) - 1.0;
442         } else {
443                 upper_height = get_height();
444         }
445
446         if (_fixed_width) {
447                 /* center display in available space
448                  * NB. this only works if the containing widget is not the
449                  * layout itself (eg. the session->property dialog)
450                  */
451                 layout_x_offset = (get_width() - layout_width)/2.0;
452         } else {
453                 /* left justify */
454                 layout_x_offset = 0;
455         }
456 }
457
458 void
459 AudioClock::on_size_request (Gtk::Requisition* req)
460 {
461         /* even for non fixed width clocks, the size we *ask* for never changes,
462            even though the size we receive might. so once we've computed it,
463            just return it.
464         */
465
466         if (first_width) {
467                 req->width = first_width;
468                 req->height = first_height;
469                 return;
470         }
471
472         Glib::RefPtr<Pango::Layout> tmp;
473         Glib::RefPtr<Gtk::Style> style = get_style ();
474         Pango::FontDescription font;
475
476         tmp = Pango::Layout::create (get_pango_context());
477
478         if (!is_realized()) {
479                 font = get_font_for_style (get_name());
480         } else {
481                 font = style->get_font();
482         }
483
484         tmp->set_font_description (font);
485
486         if (_fixed_width) {
487                 int ignored;
488                 tmp->set_text ("-88:88:88:88");
489                 tmp->get_pixel_size (_mode_width[Timecode], ignored);
490                 tmp->set_text (" 88888|88|8888");
491                 tmp->get_pixel_size (_mode_width[BBT], ignored);
492                 tmp->set_text (" 88:88:88,888");
493                 tmp->get_pixel_size (_mode_width[MinSec], ignored);
494                 tmp->set_text (" 8888888888");
495                 tmp->get_pixel_size (_mode_width[Frames], ignored);
496
497                 /* this string is the longest thing we will ever display,
498                    it does not include the BBT bar char that may descend
499                          below the baseline.
500                          note; depending on BPM setting this may actually
501                          not be sufficient for 24h worth of BBT
502                 */
503
504                 tmp->set_text (" 88888888888::,");
505         } else {
506                 switch (_mode) {
507                 case Timecode:
508                         tmp->set_text ("-88:88:88:88");
509                         break;
510                 case BBT:
511                         tmp->set_text (" 88888|88|8888");
512                         break;
513                 case MinSec:
514                         tmp->set_text (" 88:88:88,888");
515                         break;
516                 case Frames:
517                         tmp->set_text (" 8888888888");
518                         break;
519                 }
520         }
521
522         tmp->get_pixel_size (req->width, req->height);
523
524         layout_height = req->height;
525         layout_width = req->width;
526
527         /* now tackle height, for which we need to know the height of the lower
528          * layout
529          */
530
531         if (_left_layout) {
532
533                 int w;
534
535                 font.set_size ((int) lrint (font.get_size() * info_font_scale_factor));
536                 font.set_weight (Pango::WEIGHT_NORMAL);
537                 tmp->set_font_description (font);
538
539                 /* we only care about height, so put as much stuff in here
540                    as possible that might change the height.
541                 */
542                 tmp->set_text ("qyhH|"); /* one ascender, one descender */
543
544                 tmp->get_pixel_size (w, info_height);
545
546                 /* silly extra padding that seems necessary to correct the info
547                  * that pango just gave us. I have no idea why.
548                  */
549
550                 req->height += info_height;
551                 req->height += separator_height;
552         }
553
554         first_height = req->height;
555         first_width = req->width;
556 }
557
558 void
559 AudioClock::show_edit_status (int length)
560 {
561         editing_attr->set_start_index (edit_string.length() - length);
562         editing_attr->set_end_index (edit_string.length());
563
564         editing_attributes.change (*foreground_attr);
565         editing_attributes.change (*editing_attr);
566
567         _layout->set_attributes (editing_attributes);
568 }
569
570 void
571 AudioClock::start_edit (Field f)
572 {
573         pre_edit_string = _layout->get_text ();
574         if (!insert_map.empty()) {
575                 edit_string = pre_edit_string;
576         } else {
577                 edit_string.clear ();
578                 _layout->set_text ("");
579         }
580
581         input_string.clear ();
582         editing = true;
583         edit_is_negative = false;
584
585         if (f) {
586                 input_string = get_field (f);
587                 show_edit_status (merge_input_and_edit_string ());
588                 _layout->set_text (edit_string);
589         }
590
591         queue_draw ();
592
593         Keyboard::magic_widget_grab_focus ();
594         grab_focus ();
595 }
596
597 string
598 AudioClock::get_field (Field f)
599 {
600         switch (f) {
601         case Timecode_Hours:
602                 return edit_string.substr (1, 2);
603                 break;
604         case Timecode_Minutes:
605                 return edit_string.substr (4, 2);
606                 break;
607         case Timecode_Seconds:
608                 return edit_string.substr (7, 2);
609                 break;
610         case Timecode_Frames:
611                 return edit_string.substr (10, 2);
612                 break;
613         case MS_Hours:
614                 return edit_string.substr (1, 2);
615                 break;
616         case MS_Minutes:
617                 return edit_string.substr (4, 2);
618                 break;
619         case MS_Seconds:
620                 return edit_string.substr (7, 2);
621                 break;
622         case MS_Milliseconds:
623                 return edit_string.substr (10, 3);
624                 break;
625         case Bars:
626                 return edit_string.substr (1, 3);
627                 break;
628         case Beats:
629                 return edit_string.substr (5, 2);
630                 break;
631         case Ticks:
632                 return edit_string.substr (8, 4);
633                 break;
634         case AudioFrames:
635                 return edit_string;
636                 break;
637         }
638         return "";
639 }
640
641 void
642 AudioClock::end_edit (bool modify)
643 {
644         if (modify) {
645
646                 bool ok = true;
647
648                 switch (_mode) {
649                 case Timecode:
650                         ok = timecode_validate_edit (edit_string);
651                         break;
652
653                 case BBT:
654                         ok = bbt_validate_edit (edit_string);
655                         break;
656
657                 case MinSec:
658                         ok = minsec_validate_edit (edit_string);
659                         break;
660
661                 case Frames:
662                         break;
663                 }
664
665                 if (!ok) {
666                         edit_string = pre_edit_string;
667                         input_string.clear ();
668                         _layout->set_text (edit_string);
669                         show_edit_status (0);
670                         /* edit attributes remain in use */
671                 } else {
672
673                         editing = false;
674                         framepos_t pos = 0; /* stupid gcc */
675
676                         switch (_mode) {
677                         case Timecode:
678                                 pos = frames_from_timecode_string (edit_string);
679                                 break;
680
681                         case BBT:
682                                 if (is_duration) {
683                                         pos = frame_duration_from_bbt_string (0, edit_string);
684                                 } else {
685                                         pos = frames_from_bbt_string (0, edit_string);
686                                 }
687                                 break;
688
689                         case MinSec:
690                                 pos = frames_from_minsec_string (edit_string);
691                                 break;
692
693                         case Frames:
694                                 pos = frames_from_audioframes_string (edit_string);
695                                 break;
696                         }
697
698                         set (pos, true);
699                         _layout->set_attributes (normal_attributes);
700                         ValueChanged(); /* EMIT_SIGNAL */
701                 }
702
703         } else {
704
705                 editing = false;
706                 edit_is_negative = false;
707                 _layout->set_attributes (normal_attributes);
708                 _layout->set_text (pre_edit_string);
709         }
710
711         queue_draw ();
712
713         if (!editing) {
714                 drop_focus ();
715         }
716 }
717
718 void
719 AudioClock::drop_focus ()
720 {
721         Keyboard::magic_widget_drop_focus ();
722
723         if (has_focus()) {
724
725                 /* move focus back to the default widget in the top level window */
726
727                 Widget* top = get_toplevel();
728
729                 if (top->is_toplevel ()) {
730                         Window* win = dynamic_cast<Window*> (top);
731                         win->grab_focus ();
732                 }
733         }
734 }
735
736 framecnt_t
737 AudioClock::parse_as_frames_distance (const std::string& str)
738 {
739         framecnt_t f;
740
741         if (sscanf (str.c_str(), "%" PRId64, &f) == 1) {
742                 return f;
743         }
744
745         return 0;
746 }
747
748 framecnt_t
749 AudioClock::parse_as_minsec_distance (const std::string& str)
750 {
751         framecnt_t sr = _session->frame_rate();
752         int msecs;
753         int secs;
754         int mins;
755         int hrs;
756
757         switch (str.length()) {
758         case 0:
759                 return 0;
760         case 1:
761         case 2:
762         case 3:
763         case 4:
764                 sscanf (str.c_str(), "%" PRId32, &msecs);
765                 return msecs * (sr / 1000);
766
767         case 5:
768                 sscanf (str.c_str(), "%1" PRId32 "%" PRId32, &secs, &msecs);
769                 return (secs * sr) + (msecs * (sr/1000));
770
771         case 6:
772                 sscanf (str.c_str(), "%2" PRId32 "%" PRId32, &secs, &msecs);
773                 return (secs * sr) + (msecs * (sr/1000));
774
775         case 7:
776                 sscanf (str.c_str(), "%1" PRId32 "%2" PRId32 "%" PRId32, &mins, &secs, &msecs);
777                 return (mins * 60 * sr) + (secs * sr) + (msecs * (sr/1000));
778
779         case 8:
780                 sscanf (str.c_str(), "%2" PRId32 "%2" PRId32 "%" PRId32, &mins, &secs, &msecs);
781                 return (mins * 60 * sr) + (secs * sr) + (msecs * (sr/1000));
782
783         case 9:
784                 sscanf (str.c_str(), "%1" PRId32 "%2" PRId32 "%2" PRId32 "%" PRId32, &hrs, &mins, &secs, &msecs);
785                 return (hrs * 3600 * sr) + (mins * 60 * sr) + (secs * sr) + (msecs * (sr/1000));
786
787         case 10:
788                 sscanf (str.c_str(), "%1" PRId32 "%2" PRId32 "%2" PRId32 "%" PRId32, &hrs, &mins, &secs, &msecs);
789                 return (hrs * 3600 * sr) + (mins * 60 * sr) + (secs * sr) + (msecs * (sr/1000));
790
791         default:
792                 break;
793         }
794
795         return 0;
796 }
797
798 framecnt_t
799 AudioClock::parse_as_timecode_distance (const std::string& str)
800 {
801         double fps = _session->timecode_frames_per_second();
802         framecnt_t sr = _session->frame_rate();
803         int frames;
804         int secs;
805         int mins;
806         int hrs;
807
808         switch (str.length()) {
809         case 0:
810                 return 0;
811         case 1:
812         case 2:
813                 sscanf (str.c_str(), "%" PRId32, &frames);
814                 return lrint ((frames/(float)fps) * sr);
815
816         case 3:
817                 sscanf (str.c_str(), "%1" PRId32 "%" PRId32, &secs, &frames);
818                 return (secs * sr) + lrint ((frames/(float)fps) * sr);
819
820         case 4:
821                 sscanf (str.c_str(), "%2" PRId32 "%" PRId32, &secs, &frames);
822                 return (secs * sr) + lrint ((frames/(float)fps) * sr);
823
824         case 5:
825                 sscanf (str.c_str(), "%1" PRId32 "%2" PRId32 "%" PRId32, &mins, &secs, &frames);
826                 return (mins * 60 * sr) + (secs * sr) + lrint ((frames/(float)fps) * sr);
827
828         case 6:
829                 sscanf (str.c_str(), "%2" PRId32 "%2" PRId32 "%" PRId32, &mins, &secs, &frames);
830                 return (mins * 60 * sr) + (secs * sr) + lrint ((frames/(float)fps) * sr);
831
832         case 7:
833                 sscanf (str.c_str(), "%1" PRId32 "%2" PRId32 "%2" PRId32 "%" PRId32, &hrs, &mins, &secs, &frames);
834                 return (hrs * 3600 * sr) + (mins * 60 * sr) + (secs * sr) + lrint ((frames/(float)fps) * sr);
835
836         case 8:
837                 sscanf (str.c_str(), "%2" PRId32 "%2" PRId32 "%2" PRId32 "%" PRId32, &hrs, &mins, &secs, &frames);
838                 return (hrs * 3600 * sr) + (mins * 60 * sr) + (secs * sr) + lrint ((frames/(float)fps) * sr);
839
840         default:
841                 break;
842         }
843
844         return 0;
845 }
846
847 framecnt_t
848 AudioClock::parse_as_bbt_distance (const std::string&)
849 {
850         return 0;
851 }
852
853 framecnt_t
854 AudioClock::parse_as_distance (const std::string& instr)
855 {
856         switch (_mode) {
857         case Timecode:
858                 return parse_as_timecode_distance (instr);
859                 break;
860         case Frames:
861                 return parse_as_frames_distance (instr);
862                 break;
863         case BBT:
864                 return parse_as_bbt_distance (instr);
865                 break;
866         case MinSec:
867                 return parse_as_minsec_distance (instr);
868                 break;
869         }
870         return 0;
871 }
872
873 void
874 AudioClock::end_edit_relative (bool add)
875 {
876         bool ok = true;
877
878         switch (_mode) {
879         case Timecode:
880                 ok = timecode_validate_edit (edit_string);
881                 break;
882
883         case BBT:
884                 ok = bbt_validate_edit (edit_string);
885                 break;
886
887         case MinSec:
888                 ok = minsec_validate_edit (edit_string);
889                 break;
890
891         case Frames:
892                 break;
893         }
894
895         if (!ok) {
896                 edit_string = pre_edit_string;
897                 input_string.clear ();
898                 _layout->set_text (edit_string);
899                 show_edit_status (0);
900                 /* edit attributes remain in use */
901                 queue_draw ();
902                 return;
903         }
904
905         framecnt_t frames = parse_as_distance (input_string);
906
907         editing = false;
908
909         editing = false;
910         _layout->set_attributes (normal_attributes);
911
912         if (frames != 0) {
913                 if (add) {
914                         set (current_time() + frames, true);
915                 } else {
916                         framepos_t c = current_time();
917
918                         if (c > frames || _negative_allowed) {
919                                 set (c - frames, true);
920                         } else {
921                                 set (0, true);
922                         }
923                 }
924                 ValueChanged (); /* EMIT SIGNAL */
925         }
926
927         input_string.clear ();
928         queue_draw ();
929         drop_focus ();
930 }
931
932 void
933 AudioClock::session_property_changed (const PropertyChange& p)
934 {
935         set (last_when, true);
936 }
937
938 void
939 AudioClock::session_configuration_changed (std::string p)
940 {
941         if (_negative_allowed) {
942                 /* session option editor clock */
943                 return;
944         }
945
946         if (p == "sync-source" || p == "external-sync") {
947                 set (current_time(), true);
948                 return;
949         }
950
951         if (p != "timecode-offset" && p != "timecode-offset-negative") {
952                 return;
953         }
954
955         framecnt_t current;
956
957         switch (_mode) {
958         case Timecode:
959                 if (is_duration) {
960                         current = current_duration ();
961                 } else {
962                         current = current_time ();
963                 }
964                 set (current, true);
965                 break;
966         default:
967                 break;
968         }
969 }
970
971 void
972 AudioClock::set (framepos_t when, bool force, framecnt_t offset)
973 {
974         if ((!force && !is_visible()) || _session == 0) {
975                 return;
976         }
977
978         if (is_duration) {
979                 when = when - offset;
980         }
981
982         if (when == last_when && !force) {
983                 if (_mode != Timecode && _mode != MinSec) {
984                         /* may need to force display of TC source
985                          * time, so don't return early.
986                          */
987                         return;
988                 }
989         }
990
991         if (!editing) {
992                 if (_right_layout) {
993                         _right_layout->set_alignment(Pango::ALIGN_LEFT);
994                 }
995
996                 switch (_mode) {
997                 case Timecode:
998                         if (_right_layout) {
999                                 _right_layout->set_alignment(Pango::ALIGN_RIGHT);
1000                         }
1001                         set_timecode (when, force);
1002                         break;
1003
1004                 case BBT:
1005                         set_bbt (when, force);
1006                         break;
1007
1008                 case MinSec:
1009                         if (_right_layout) {
1010                                 _right_layout->set_alignment(Pango::ALIGN_RIGHT);
1011                         }
1012                         set_minsec (when, force);
1013                         break;
1014
1015                 case Frames:
1016                         set_frames (when, force);
1017                         break;
1018                 }
1019         }
1020
1021         queue_draw ();
1022         last_when = when;
1023 }
1024
1025 void
1026 AudioClock::set_slave_info ()
1027 {
1028         if (!_left_layout || !_right_layout) {
1029                 return;
1030         }
1031
1032         SyncSource sync_src = Config->get_sync_source();
1033
1034         if (_session->config.get_external_sync()) {
1035                 Slave* slave = _session->slave();
1036
1037                 switch (sync_src) {
1038                 case JACK:
1039                         _left_layout->set_markup (string_compose ("<span size=\"%1\" foreground=\"white\">%2</span>",
1040                                                 INFO_FONT_SIZE, sync_source_to_string(sync_src, true)));
1041                         _right_layout->set_text ("");
1042                         break;
1043                 case MIDIClock:
1044                         if (slave) {
1045                                 _left_layout->set_markup (string_compose ("<span size=\"%1\" foreground=\"white\">%2</span>",
1046                                                         INFO_FONT_SIZE, sync_source_to_string(sync_src, true)));
1047                                 _right_layout->set_markup (string_compose ("<span size=\"%1\" foreground=\"white\">%2</span>",
1048                                                         INFO_FONT_SIZE, slave->approximate_current_delta()));
1049                         } else {
1050                                 _left_layout->set_markup (string_compose ("<span size=\"%1\" foreground=\"white\">%2</span>",
1051                                                         INFO_FONT_SIZE, _("--pending--")));
1052                                 _right_layout->set_text ("");
1053                         }
1054                         break;
1055                 case LTC:
1056                 case MTC:
1057                         if (slave) {
1058                                 bool matching;
1059                                 TimecodeSlave* tcslave;
1060                                 if ((tcslave = dynamic_cast<TimecodeSlave*>(_session->slave())) != 0) {
1061                                         matching = (tcslave->apparent_timecode_format() == _session->config.get_timecode_format());
1062                                         _left_layout->set_markup (string_compose ("<span size=\"%1\"><span foreground=\"white\">%2</span><span foreground=\"%3\">%4</span></span>",
1063                                                                                   INFO_FONT_SIZE, sync_source_to_string(sync_src, true)[0], (matching?"green":"red"),
1064                                                                                   dynamic_cast<TimecodeSlave*>(slave)->approximate_current_position()));
1065                                         _right_layout->set_markup (string_compose ("<span size=\"%1\" foreground=\"white\">%2</span>",
1066                                                                                    INFO_FONT_SIZE, slave->approximate_current_delta()));
1067                                 }
1068                         } else {
1069                                 _left_layout->set_markup (string_compose ("<span size=\"%1\" foreground=\"white\">%2</span>",
1070                                                         INFO_FONT_SIZE, _("--pending--")));
1071                                 _right_layout->set_text ("");
1072                         }
1073                         break;
1074                 }
1075         } else {
1076                 _left_layout->set_markup (string_compose ("<span size=\"%1\" foreground=\"white\">INT/%2</span>",
1077                                         INFO_FONT_SIZE, sync_source_to_string(sync_src, true)));
1078                 _right_layout->set_text ("");
1079         }
1080 }
1081
1082 void
1083 AudioClock::set_frames (framepos_t when, bool /*force*/)
1084 {
1085         char buf[32];
1086         bool negative = false;
1087
1088         if (_off) {
1089                 _layout->set_text ("\u2012\u2012\u2012\u2012\u2012\u2012\u2012\u2012\u2012\u2012");
1090
1091                 if (_left_layout) {
1092                         _left_layout->set_text ("");
1093                         _right_layout->set_text ("");
1094                 }
1095
1096                 return;
1097         }
1098
1099         if (when < 0) {
1100                 when = -when;
1101                 negative = true;
1102         }
1103
1104         if (negative) {
1105                 snprintf (buf, sizeof (buf), "-%10" PRId64, when);
1106         } else {
1107                 snprintf (buf, sizeof (buf), " %10" PRId64, when);
1108         }
1109
1110         _layout->set_text (buf);
1111
1112         if (_left_layout) {
1113                 framecnt_t rate = _session->frame_rate();
1114
1115                 if (fmod (rate, 100.0) == 0.0) {
1116                         sprintf (buf, "%.1fkHz", rate/1000.0);
1117                 } else {
1118                         sprintf (buf, "%" PRId64 "Hz", rate);
1119                 }
1120
1121                 _left_layout->set_markup (string_compose ("<span size=\"%1\"><span foreground=\"white\">%2 </span><span foreground=\"green\">%3</span></span>",
1122                                 INFO_FONT_SIZE, _("SR"), buf));
1123
1124                 float vid_pullup = _session->config.get_video_pullup();
1125
1126                 if (vid_pullup == 0.0) {
1127                         _right_layout->set_markup (string_compose ("<span size=\"%1\"><span foreground=\"white\">%2 </span><span foreground=\"green\">off</span></span>",
1128                                         INFO_FONT_SIZE, _("Pull")));
1129                 } else {
1130                         sprintf (buf, _("%+.4f%%"), vid_pullup);
1131                         _right_layout->set_markup (string_compose ("<span size=\"%1\"><span foreground=\"white\">%2 </span><span foreground=\"green\">%3</span></span>",
1132                                         INFO_FONT_SIZE, _("Pull"), buf));
1133                 }
1134         }
1135 }
1136
1137 void
1138 AudioClock::set_minsec (framepos_t when, bool /*force*/)
1139 {
1140         char buf[32];
1141         framecnt_t left;
1142         int hrs;
1143         int mins;
1144         int secs;
1145         int millisecs;
1146         bool negative = false;
1147
1148         if (_off) {
1149                 _layout->set_text ("\u2012\u2012:\u2012\u2012:\u2012\u2012.\u2012\u2012\u2012");
1150
1151                 if (_left_layout) {
1152                         _left_layout->set_text ("");
1153                         _right_layout->set_text ("");
1154                 }
1155
1156                 return;
1157         }
1158
1159         if (when < 0) {
1160                 when = -when;
1161                 negative = true;
1162         }
1163
1164         left = when;
1165         hrs = (int) floor (left / (_session->frame_rate() * 60.0f * 60.0f));
1166         left -= (framecnt_t) floor (hrs * _session->frame_rate() * 60.0f * 60.0f);
1167         mins = (int) floor (left / (_session->frame_rate() * 60.0f));
1168         left -= (framecnt_t) floor (mins * _session->frame_rate() * 60.0f);
1169         secs = (int) floor (left / (float) _session->frame_rate());
1170         left -= (framecnt_t) floor (secs * _session->frame_rate());
1171         millisecs = floor (left * 1000.0 / (float) _session->frame_rate());
1172
1173         if (negative) {
1174                 snprintf (buf, sizeof (buf), "-%02" PRId32 ":%02" PRId32 ":%02" PRId32 ".%03" PRId32, hrs, mins, secs, millisecs);
1175         } else {
1176                 snprintf (buf, sizeof (buf), " %02" PRId32 ":%02" PRId32 ":%02" PRId32 ".%03" PRId32, hrs, mins, secs, millisecs);
1177         }
1178
1179         _layout->set_text (buf);
1180         set_slave_info();
1181 }
1182
1183 void
1184 AudioClock::set_timecode (framepos_t when, bool /*force*/)
1185 {
1186         Timecode::Time TC;
1187         bool negative = false;
1188
1189         if (_off) {
1190                 _layout->set_text ("\u2012\u2012:\u2012\u2012:\u2012\u2012:\u2012\u2012");
1191                 if (_left_layout) {
1192                         _left_layout->set_text ("");
1193                         _right_layout->set_text ("");
1194                 }
1195
1196                 return;
1197         }
1198
1199         if (when < 0) {
1200                 when = -when;
1201                 negative = true;
1202         }
1203
1204         if (is_duration) {
1205                 _session->timecode_duration (when, TC);
1206         } else {
1207                 _session->timecode_time (when, TC);
1208         }
1209
1210         TC.negative = TC.negative || negative;
1211
1212         _layout->set_text (Timecode::timecode_format_time(TC));
1213
1214         set_slave_info();
1215 }
1216
1217 void
1218 AudioClock::set_bbt (framepos_t when, bool /*force*/)
1219 {
1220         char buf[16];
1221         Timecode::BBT_Time BBT;
1222         bool negative = false;
1223
1224         if (_off) {
1225                 _layout->set_text ("\u2012\u2012\u2012|\u2012\u2012|\u2012\u2012\u2012\u2012");
1226                 if (_left_layout) {
1227                         _left_layout->set_text ("");
1228                         _right_layout->set_text ("");
1229                 }
1230                 return;
1231         }
1232
1233         if (when < 0) {
1234                 when = -when;
1235                 negative = true;
1236         }
1237
1238         /* handle a common case */
1239         if (is_duration) {
1240                 if (when == 0) {
1241                         BBT.bars = 0;
1242                         BBT.beats = 0;
1243                         BBT.ticks = 0;
1244                 } else {
1245                         _session->tempo_map().bbt_time (when, BBT);
1246                         BBT.bars--;
1247                         BBT.beats--;
1248                 }
1249         } else {
1250                 _session->tempo_map().bbt_time (when, BBT);
1251         }
1252
1253         if (negative) {
1254                 snprintf (buf, sizeof (buf), "-%03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
1255                           BBT.bars, BBT.beats, BBT.ticks);
1256         } else {
1257                 snprintf (buf, sizeof (buf), " %03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
1258                           BBT.bars, BBT.beats, BBT.ticks);
1259         }
1260
1261         _layout->set_text (buf);
1262
1263         if (_right_layout) {
1264                 framepos_t pos;
1265
1266                 if (bbt_reference_time < 0) {
1267                         pos = when;
1268                 } else {
1269                         pos = bbt_reference_time;
1270                 }
1271
1272                 TempoMetric m (_session->tempo_map().metric_at (pos));
1273
1274                 sprintf (buf, "%-5.2f", m.tempo().beats_per_minute());
1275                 _left_layout->set_markup (string_compose ("<span size=\"%1\" foreground=\"white\">Tempo <span foreground=\"green\">%2</span></span>",
1276                                         INFO_FONT_SIZE, buf));
1277
1278                 sprintf (buf, "%g/%g", m.meter().divisions_per_bar(), m.meter().note_divisor());
1279                 _right_layout->set_markup (string_compose ("<span size=\"%1\" foreground=\"white\">Meter <span foreground=\"green\">%2</span></span>",
1280                                         INFO_FONT_SIZE, buf));
1281         }
1282 }
1283
1284 void
1285 AudioClock::set_session (Session *s)
1286 {
1287         SessionHandlePtr::set_session (s);
1288
1289         if (_session) {
1290
1291                 _session->config.ParameterChanged.connect (_session_connections, invalidator (*this), boost::bind (&AudioClock::session_configuration_changed, this, _1), gui_context());
1292                 _session->tempo_map().PropertyChanged.connect (_session_connections, invalidator (*this), boost::bind (&AudioClock::session_property_changed, this, _1), gui_context());
1293
1294                 const XMLProperty* prop;
1295                 XMLNode* node = _session->extra_xml (X_("ClockModes"));
1296                 AudioClock::Mode amode;
1297
1298                 if (node) {
1299                         for (XMLNodeList::const_iterator i = node->children().begin(); i != node->children().end(); ++i) {
1300                                 if ((prop = (*i)->property (X_("name"))) && prop->value() == _name) {
1301
1302                                         if ((prop = (*i)->property (X_("mode"))) != 0) {
1303                                                 amode = AudioClock::Mode (string_2_enum (prop->value(), amode));
1304                                                 set_mode (amode);
1305                                         }
1306                                         if ((prop = (*i)->property (X_("on"))) != 0) {
1307                                                 set_off (!string_is_affirmative (prop->value()));
1308                                         }
1309                                         break;
1310                                 }
1311                         }
1312                 }
1313
1314                 set (last_when, true);
1315         }
1316 }
1317
1318 bool
1319 AudioClock::on_key_press_event (GdkEventKey* ev)
1320 {
1321         if (!editing) {
1322                 return false;
1323         }
1324
1325         string new_text;
1326         char new_char = 0;
1327         int highlight_length;
1328         framepos_t pos;
1329
1330         switch (ev->keyval) {
1331         case GDK_0:
1332         case GDK_KP_0:
1333                 new_char = '0';
1334                 break;
1335         case GDK_1:
1336         case GDK_KP_1:
1337                 new_char = '1';
1338                 break;
1339         case GDK_2:
1340         case GDK_KP_2:
1341                 new_char = '2';
1342                 break;
1343         case GDK_3:
1344         case GDK_KP_3:
1345                 new_char = '3';
1346                 break;
1347         case GDK_4:
1348         case GDK_KP_4:
1349                 new_char = '4';
1350                 break;
1351         case GDK_5:
1352         case GDK_KP_5:
1353                 new_char = '5';
1354                 break;
1355         case GDK_6:
1356         case GDK_KP_6:
1357                 new_char = '6';
1358                 break;
1359         case GDK_7:
1360         case GDK_KP_7:
1361                 new_char = '7';
1362                 break;
1363         case GDK_8:
1364         case GDK_KP_8:
1365                 new_char = '8';
1366                 break;
1367         case GDK_9:
1368         case GDK_KP_9:
1369                 new_char = '9';
1370                 break;
1371
1372         case GDK_minus:
1373         case GDK_KP_Subtract:
1374                 if (_negative_allowed && input_string.empty()) {
1375                                 edit_is_negative = true;
1376                                 edit_string.replace(0,1,"-");
1377                                 _layout->set_text (edit_string);
1378                                 queue_draw ();
1379                 } else {
1380                         end_edit_relative (false);
1381                 }
1382                 return true;
1383                 break;
1384
1385         case GDK_plus:
1386                 end_edit_relative (true);
1387                 return true;
1388                 break;
1389
1390         case GDK_Tab:
1391         case GDK_Return:
1392         case GDK_KP_Enter:
1393                 end_edit (true);
1394                 return true;
1395                 break;
1396
1397         case GDK_Escape:
1398                 end_edit (false);
1399                 ChangeAborted();  /*  EMIT SIGNAL  */
1400                 return true;
1401
1402         case GDK_Delete:
1403         case GDK_BackSpace:
1404                 if (!input_string.empty()) {
1405                         /* delete the last key entered
1406                         */
1407                         input_string = input_string.substr (0, input_string.length() - 1);
1408                 }
1409                 goto use_input_string;
1410
1411         default:
1412                 return false;
1413         }
1414
1415         if (!insert_map.empty() && (input_string.length() >= insert_map.size())) {
1416                 /* too many digits: eat the key event, but do nothing with it */
1417                 return true;
1418         }
1419
1420         input_string.push_back (new_char);
1421
1422   use_input_string:
1423
1424         switch (_mode) {
1425         case Frames:
1426                 /* get this one in the right order, and to the right width */
1427                 if (ev->keyval == GDK_Delete || ev->keyval == GDK_BackSpace) {
1428                         edit_string = edit_string.substr (0, edit_string.length() - 1);
1429                 } else {
1430                         edit_string.push_back (new_char);
1431                 }
1432                 if (!edit_string.empty()) {
1433                         char buf[32];
1434                         sscanf (edit_string.c_str(), "%" PRId64, &pos);
1435                         snprintf (buf, sizeof (buf), " %10" PRId64, pos);
1436                         edit_string = buf;
1437                 }
1438                 /* highlight the whole thing */
1439                 highlight_length = edit_string.length();
1440                 break;
1441
1442         default:
1443                 highlight_length = merge_input_and_edit_string ();
1444         }
1445
1446         if (edit_is_negative) {
1447                 edit_string.replace(0,1,"-");
1448         } else {
1449                 if (pre_edit_string.at(0) == '-') {
1450                         edit_string.replace(0,1,"_");
1451                 } else {
1452                         edit_string.replace(0,1," ");
1453                 }
1454         }
1455
1456         show_edit_status (highlight_length);
1457         _layout->set_text (edit_string);
1458         queue_draw ();
1459
1460         return true;
1461 }
1462
1463 int
1464 AudioClock::merge_input_and_edit_string ()
1465 {
1466         /* merge with pre-edit-string into edit string */
1467
1468         edit_string = pre_edit_string;
1469
1470         if (input_string.empty()) {
1471                 return 0;
1472         }
1473
1474         string::size_type target;
1475         for (string::size_type i = 0; i < input_string.length(); ++i) {
1476                 target = insert_map[input_string.length() - 1 - i];
1477                 edit_string[target] = input_string[i];
1478         }
1479         /* highlight from end to wherever the last character was added */
1480         return edit_string.length() - insert_map[input_string.length()-1];
1481 }
1482
1483
1484 bool
1485 AudioClock::on_key_release_event (GdkEventKey *ev)
1486 {
1487         if (!editing) {
1488                 return false;
1489         }
1490
1491         /* return true for keys that we used on press
1492            so that they cannot possibly do double-duty
1493         */
1494         switch (ev->keyval) {
1495         case GDK_0:
1496         case GDK_KP_0:
1497         case GDK_1:
1498         case GDK_KP_1:
1499         case GDK_2:
1500         case GDK_KP_2:
1501         case GDK_3:
1502         case GDK_KP_3:
1503         case GDK_4:
1504         case GDK_KP_4:
1505         case GDK_5:
1506         case GDK_KP_5:
1507         case GDK_6:
1508         case GDK_KP_6:
1509         case GDK_7:
1510         case GDK_KP_7:
1511         case GDK_8:
1512         case GDK_KP_8:
1513         case GDK_9:
1514         case GDK_KP_9:
1515         case GDK_period:
1516         case GDK_comma:
1517         case GDK_KP_Decimal:
1518         case GDK_Tab:
1519         case GDK_Return:
1520         case GDK_KP_Enter:
1521         case GDK_Escape:
1522         case GDK_minus:
1523         case GDK_plus:
1524         case GDK_KP_Add:
1525         case GDK_KP_Subtract:
1526                 return true;
1527         default:
1528                 return false;
1529         }
1530 }
1531
1532 AudioClock::Field
1533 AudioClock::index_to_field (int index) const
1534 {
1535         switch (_mode) {
1536         case Timecode:
1537                 if (index < 4) {
1538                         return Timecode_Hours;
1539                 } else if (index < 7) {
1540                         return Timecode_Minutes;
1541                 } else if (index < 10) {
1542                         return Timecode_Seconds;
1543                 } else {
1544                         return Timecode_Frames;
1545                 }
1546                 break;
1547         case BBT:
1548                 if (index < 5) {
1549                         return Bars;
1550                 } else if (index < 7) {
1551                         return Beats;
1552                 } else {
1553                         return Ticks;
1554                 }
1555                 break;
1556         case MinSec:
1557                 if (index < 3) {
1558                         return Timecode_Hours;
1559                 } else if (index < 6) {
1560                         return MS_Minutes;
1561                 } else if (index < 9) {
1562                         return MS_Seconds;
1563                 } else {
1564                         return MS_Milliseconds;
1565                 }
1566                 break;
1567         case Frames:
1568                 return AudioFrames;
1569                 break;
1570         }
1571
1572         return Field (0);
1573 }
1574
1575 bool
1576 AudioClock::on_button_press_event (GdkEventButton *ev)
1577 {
1578         switch (ev->button) {
1579         case 1:
1580                 if (editable && !_off) {
1581                         int index;
1582                         int trailing;
1583                         int y;
1584                         int x;
1585
1586                         /* the text has been centered vertically, so adjust
1587                          * x and y.
1588                          */
1589                         int xcenter = !_fixed_width || layout_x_offset > 0 ? 0 : (get_width() - _mode_width[_mode]) /2;
1590
1591                         y = ev->y - ((upper_height - layout_height)/2);
1592                         x = ev->x - layout_x_offset - xcenter;
1593
1594                         if (!_layout->xy_to_index (x * PANGO_SCALE, y * PANGO_SCALE, index, trailing)) {
1595                                 /* pretend it is a character on the far right */
1596                                 index = 99;
1597                         }
1598                         drag_field = index_to_field (index);
1599                         dragging = true;
1600                         /* make absolutely sure that the pointer is grabbed */
1601                         gdk_pointer_grab(ev->window,false ,
1602                                          GdkEventMask( Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_PRESS_MASK |Gdk::BUTTON_RELEASE_MASK),
1603                                          NULL,NULL,ev->time);
1604                         drag_accum = 0;
1605                         drag_start_y = ev->y;
1606                         drag_y = ev->y;
1607                 }
1608                 break;
1609
1610         default:
1611                 return false;
1612                 break;
1613         }
1614
1615         return true;
1616 }
1617
1618 bool
1619 AudioClock::on_button_release_event (GdkEventButton *ev)
1620 {
1621         if (editable && !_off) {
1622                 if (dragging) {
1623                         gdk_pointer_ungrab (GDK_CURRENT_TIME);
1624                         dragging = false;
1625                         if (ev->y > drag_start_y+1 || ev->y < drag_start_y-1 || Keyboard::modifier_state_equals (ev->state, Keyboard::TertiaryModifier)){
1626                                 // we actually dragged so return without
1627                                 // setting editing focus, or we shift clicked
1628                                 return true;
1629                         } else {
1630                                 if (ev->button == 1) {
1631
1632                                         if (_edit_by_click_field) {
1633
1634                                                 int xcenter = !_fixed_width || layout_x_offset > 0 ? 0 : (get_width() - _mode_width[_mode]) /2;
1635                                                 int index = 0;
1636                                                 int trailing;
1637                                                 int y = ev->y - ((upper_height - layout_height)/2);
1638                                                 int x = ev->x - layout_x_offset - xcenter;
1639                                                 Field f;
1640
1641                                                 if (!_layout->xy_to_index (x * PANGO_SCALE, y * PANGO_SCALE, index, trailing)) {
1642                                                         return true;
1643                                                 }
1644
1645                                                 f = index_to_field (index);
1646
1647                                                 switch (f) {
1648                                                 case Timecode_Frames:
1649                                                 case MS_Milliseconds:
1650                                                 case Ticks:
1651                                                         f = Field (0);
1652                                                         break;
1653                                                 default:
1654                                                         break;
1655                                                 }
1656                                                 start_edit (f);
1657                                         } else {
1658                                                 start_edit ();
1659                                         }
1660                                 }
1661                         }
1662                 }
1663         }
1664
1665         if (Keyboard::is_context_menu_event (ev)) {
1666                 if (ops_menu == 0) {
1667                         build_ops_menu ();
1668                 }
1669                 ops_menu->popup (1, ev->time);
1670                 return true;
1671         }
1672
1673         return false;
1674 }
1675
1676 bool
1677 AudioClock::on_focus_out_event (GdkEventFocus* ev)
1678 {
1679         bool ret = CairoWidget::on_focus_out_event (ev);
1680
1681         if (editing) {
1682                 end_edit (false);
1683         }
1684
1685         return ret;
1686 }
1687
1688 bool
1689 AudioClock::on_scroll_event (GdkEventScroll *ev)
1690 {
1691         int index;
1692         int trailing;
1693
1694         if (editing || _session == 0 || !editable || _off) {
1695                 return false;
1696         }
1697
1698         int y;
1699         int x;
1700
1701         /* the text has been centered vertically, so adjust
1702          * x and y.
1703          */
1704
1705         int xcenter = !_fixed_width || layout_x_offset > 0 ? 0 : (get_width() - _mode_width[_mode]) /2;
1706         y = ev->y - ((upper_height - layout_height)/2);
1707         x = ev->x - layout_x_offset - xcenter;
1708
1709         if (!_layout->xy_to_index (x * PANGO_SCALE, y * PANGO_SCALE, index, trailing)) {
1710                 /* not in the main layout */
1711                 return false;
1712         }
1713
1714         Field f = index_to_field (index);
1715         framepos_t frames = 0;
1716
1717         switch (ev->direction) {
1718
1719         case GDK_SCROLL_UP:
1720                 frames = get_frame_step (f);
1721                 if (frames != 0) {
1722                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
1723                                 frames *= 10;
1724                         }
1725                         set (current_time() + frames, true);
1726                         ValueChanged (); /* EMIT_SIGNAL */
1727                 }
1728                 break;
1729
1730         case GDK_SCROLL_DOWN:
1731                 frames = get_frame_step (f);
1732                 if (frames != 0) {
1733                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
1734                                 frames *= 10;
1735                         }
1736
1737                         if (!_negative_allowed && (double)current_time() - (double)frames < 0.0) {
1738                                 set (0, true);
1739                         } else {
1740                                 set (current_time() - frames, true);
1741                         }
1742
1743                         ValueChanged (); /* EMIT_SIGNAL */
1744                 }
1745                 break;
1746
1747         default:
1748                 return false;
1749                 break;
1750         }
1751
1752         return true;
1753 }
1754
1755 bool
1756 AudioClock::on_motion_notify_event (GdkEventMotion *ev)
1757 {
1758         if (editing || _session == 0 || !dragging) {
1759                 return false;
1760         }
1761
1762         float pixel_frame_scale_factor = 0.2f;
1763
1764         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier))  {
1765                 pixel_frame_scale_factor = 0.1f;
1766         }
1767
1768
1769         if (Keyboard::modifier_state_contains (ev->state,
1770                                                Keyboard::PrimaryModifier|Keyboard::SecondaryModifier)) {
1771
1772                 pixel_frame_scale_factor = 0.025f;
1773         }
1774
1775         double y_delta = ev->y - drag_y;
1776
1777         drag_accum +=  y_delta*pixel_frame_scale_factor;
1778
1779         drag_y = ev->y;
1780
1781         if (trunc (drag_accum) != 0) {
1782
1783                 framepos_t frames;
1784                 framepos_t pos;
1785                 int dir;
1786                 dir = (drag_accum < 0 ? 1:-1);
1787                 pos = current_time();
1788                 frames = get_frame_step (drag_field, pos, dir);
1789
1790                 if (frames  != 0 &&  frames * drag_accum < current_time()) {
1791                         set ((framepos_t) floor (pos - drag_accum * frames), false); // minus because up is negative in GTK
1792                 } else {
1793                         set (0 , false);
1794                 }
1795
1796                 drag_accum= 0;
1797                 ValueChanged();  /* EMIT_SIGNAL */
1798         }
1799
1800         return true;
1801 }
1802
1803 framepos_t
1804 AudioClock::get_frame_step (Field field, framepos_t pos, int dir)
1805 {
1806         framecnt_t f = 0;
1807         Timecode::BBT_Time BBT;
1808         switch (field) {
1809         case Timecode_Hours:
1810                 f = (framecnt_t) floor (3600.0 * _session->frame_rate());
1811                 break;
1812         case Timecode_Minutes:
1813                 f = (framecnt_t) floor (60.0 * _session->frame_rate());
1814                 break;
1815         case Timecode_Seconds:
1816                 f = _session->frame_rate();
1817                 break;
1818         case Timecode_Frames:
1819                 f = (framecnt_t) floor (_session->frame_rate() / _session->timecode_frames_per_second());
1820                 break;
1821
1822         case AudioFrames:
1823                 f = 1;
1824                 break;
1825
1826         case MS_Hours:
1827                 f = (framecnt_t) floor (3600.0 * _session->frame_rate());
1828                 break;
1829         case MS_Minutes:
1830                 f = (framecnt_t) floor (60.0 * _session->frame_rate());
1831                 break;
1832         case MS_Seconds:
1833                 f = (framecnt_t) _session->frame_rate();
1834                 break;
1835         case MS_Milliseconds:
1836                 f = (framecnt_t) floor (_session->frame_rate() / 1000.0);
1837                 break;
1838
1839         case Bars:
1840                 BBT.bars = 1;
1841                 BBT.beats = 0;
1842                 BBT.ticks = 0;
1843                 f = _session->tempo_map().bbt_duration_at (pos,BBT,dir);
1844                 break;
1845         case Beats:
1846                 BBT.bars = 0;
1847                 BBT.beats = 1;
1848                 BBT.ticks = 0;
1849                 f = _session->tempo_map().bbt_duration_at(pos,BBT,dir);
1850                 break;
1851         case Ticks:
1852                 BBT.bars = 0;
1853                 BBT.beats = 0;
1854                 BBT.ticks = 1;
1855                 f = _session->tempo_map().bbt_duration_at(pos,BBT,dir);
1856                 break;
1857         default:
1858                 error << string_compose (_("programming error: %1"), "attempt to get frames from non-text field!") << endmsg;
1859                 f = 0;
1860                 break;
1861         }
1862
1863         return f;
1864 }
1865
1866 framepos_t
1867 AudioClock::current_time (framepos_t) const
1868 {
1869         return last_when;
1870 }
1871
1872 framepos_t
1873 AudioClock::current_duration (framepos_t pos) const
1874 {
1875         framepos_t ret = 0;
1876
1877         switch (_mode) {
1878         case Timecode:
1879                 ret = last_when;
1880                 break;
1881         case BBT:
1882                 ret = frame_duration_from_bbt_string (pos, _layout->get_text());
1883                 break;
1884
1885         case MinSec:
1886                 ret = last_when;
1887                 break;
1888
1889         case Frames:
1890                 ret = last_when;
1891                 break;
1892         }
1893
1894         return ret;
1895 }
1896
1897 bool
1898 AudioClock::bbt_validate_edit (const string& str)
1899 {
1900         AnyTime any;
1901
1902         if (sscanf (str.c_str(), BBT_SCANF_FORMAT, &any.bbt.bars, &any.bbt.beats, &any.bbt.ticks) != 3) {
1903                 return false;
1904         }
1905
1906         if (any.bbt.ticks > Timecode::BBT_Time::ticks_per_beat) {
1907                 return false;
1908         }
1909
1910         if (!is_duration && any.bbt.bars == 0) {
1911                 return false;
1912         }
1913
1914         if (!is_duration && any.bbt.beats == 0) {
1915                 return false;
1916         }
1917
1918         return true;
1919 }
1920
1921 bool
1922 AudioClock::timecode_validate_edit (const string&)
1923 {
1924         Timecode::Time TC;
1925         int hours;
1926         char ignored[2];
1927
1928         if (sscanf (_layout->get_text().c_str(), "%[- _]%" PRId32 ":%" PRId32 ":%" PRId32 "%[:;]%" PRId32,
1929                     ignored, &hours, &TC.minutes, &TC.seconds, ignored, &TC.frames) != 6) {
1930                 return false;
1931         }
1932
1933         if (hours < 0) {
1934                 TC.hours = hours * -1;
1935                 TC.negative = true;
1936         } else {
1937                 TC.hours = hours;
1938                 TC.negative = false;
1939         }
1940
1941         if (TC.negative && !_negative_allowed) {
1942                 return false;
1943         }
1944
1945         if (TC.hours > 23U || TC.minutes > 59U || TC.seconds > 59U) {
1946                 return false;
1947         }
1948
1949         if (TC.frames > (uint32_t) rint (_session->timecode_frames_per_second()) - 1) {
1950                 return false;
1951         }
1952
1953         if (_session->timecode_drop_frames()) {
1954                 if (TC.minutes % 10 && TC.seconds == 0U && TC.frames < 2U) {
1955                         return false;
1956                 }
1957         }
1958
1959         return true;
1960 }
1961
1962 bool
1963 AudioClock::minsec_validate_edit (const string& str)
1964 {
1965         int hrs, mins, secs, millisecs;
1966
1967         if (sscanf (str.c_str(), "%d:%d:%d.%d", &hrs, &mins, &secs, &millisecs) != 4) {
1968                 return false;
1969         }
1970
1971         if (hrs > 23 || mins > 59 || secs > 59 || millisecs > 999) {
1972                 return false;
1973         }
1974
1975         return true;
1976 }
1977
1978 framepos_t
1979 AudioClock::frames_from_timecode_string (const string& str) const
1980 {
1981         if (_session == 0) {
1982                 return 0;
1983         }
1984
1985         Timecode::Time TC;
1986         framepos_t sample;
1987         char ignored[2];
1988         int hours;
1989
1990         if (sscanf (str.c_str(), "%[- _]%d:%d:%d%[:;]%d", ignored, &hours, &TC.minutes, &TC.seconds, ignored, &TC.frames) != 6) {
1991                 error << string_compose (_("programming error: %1 %2"), "badly formatted timecode clock string", str) << endmsg;
1992                 return 0;
1993         }
1994         TC.hours = abs(hours);
1995         TC.rate = _session->timecode_frames_per_second();
1996         TC.drop= _session->timecode_drop_frames();
1997
1998         _session->timecode_to_sample (TC, sample, false /* use_offset */, false /* use_subframes */ );
1999
2000         // timecode_tester ();
2001         if (edit_is_negative) {
2002                 sample = - sample;
2003         }
2004
2005         return sample;
2006 }
2007
2008 framepos_t
2009 AudioClock::frames_from_minsec_string (const string& str) const
2010 {
2011         if (_session == 0) {
2012                 return 0;
2013         }
2014
2015         int hrs, mins, secs, millisecs;
2016         framecnt_t sr = _session->frame_rate();
2017
2018         if (sscanf (str.c_str(), "%d:%d:%d.%d", &hrs, &mins, &secs, &millisecs) != 4) {
2019                 error << string_compose (_("programming error: %1 %2"), "badly formatted minsec clock string", str) << endmsg;
2020                 return 0;
2021         }
2022
2023         return (framepos_t) floor ((hrs * 60.0f * 60.0f * sr) + (mins * 60.0f * sr) + (secs * sr) + (millisecs * sr / 1000.0));
2024 }
2025
2026 framepos_t
2027 AudioClock::frames_from_bbt_string (framepos_t pos, const string& str) const
2028 {
2029         if (_session == 0) {
2030                 error << "AudioClock::current_time() called with BBT mode but without session!" << endmsg;
2031                 return 0;
2032         }
2033
2034         AnyTime any;
2035         any.type = AnyTime::BBT;
2036
2037         if (sscanf (str.c_str(), BBT_SCANF_FORMAT, &any.bbt.bars, &any.bbt.beats, &any.bbt.ticks) != 3) {
2038                 return 0;
2039         }
2040
2041         if (is_duration) {
2042                 any.bbt.bars++;
2043                 any.bbt.beats++;
2044                 return _session->any_duration_to_frames (pos, any);
2045         } else {
2046                 return _session->convert_to_frames (any);
2047         }
2048 }
2049
2050
2051 framepos_t
2052 AudioClock::frame_duration_from_bbt_string (framepos_t pos, const string& str) const
2053 {
2054         if (_session == 0) {
2055                 error << "AudioClock::current_time() called with BBT mode but without session!" << endmsg;
2056                 return 0;
2057         }
2058
2059         Timecode::BBT_Time bbt;
2060
2061         if (sscanf (str.c_str(), BBT_SCANF_FORMAT, &bbt.bars, &bbt.beats, &bbt.ticks) != 3) {
2062                 return 0;
2063         }
2064
2065         return _session->tempo_map().bbt_duration_at(pos,bbt,1);
2066 }
2067
2068 framepos_t
2069 AudioClock::frames_from_audioframes_string (const string& str) const
2070 {
2071         framepos_t f;
2072         sscanf (str.c_str(), "%" PRId64, &f);
2073         return f;
2074 }
2075
2076 void
2077 AudioClock::build_ops_menu ()
2078 {
2079         using namespace Menu_Helpers;
2080         ops_menu = new Menu;
2081         MenuList& ops_items = ops_menu->items();
2082         ops_menu->set_name ("ArdourContextMenu");
2083
2084         if (!Profile->get_sae()) {
2085                 ops_items.push_back (MenuElem (_("Timecode"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), Timecode)));
2086         }
2087         ops_items.push_back (MenuElem (_("Bars:Beats"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), BBT)));
2088         ops_items.push_back (MenuElem (_("Minutes:Seconds"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), MinSec)));
2089         ops_items.push_back (MenuElem (_("Samples"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), Frames)));
2090
2091         if (editable && !_off && !is_duration && !_follows_playhead) {
2092                 ops_items.push_back (SeparatorElem());
2093                 ops_items.push_back (MenuElem (_("Set From Playhead"), sigc::mem_fun(*this, &AudioClock::set_from_playhead)));
2094                 ops_items.push_back (MenuElem (_("Locate to This Time"), sigc::mem_fun(*this, &AudioClock::locate)));
2095         }
2096 }
2097
2098 void
2099 AudioClock::set_from_playhead ()
2100 {
2101         if (!_session) {
2102                 return;
2103         }
2104
2105         set (_session->transport_frame());
2106         ValueChanged ();
2107 }
2108
2109 void
2110 AudioClock::locate ()
2111 {
2112         if (!_session || is_duration) {
2113                 return;
2114         }
2115
2116         _session->request_locate (current_time(), _session->transport_rolling ());
2117 }
2118
2119 void
2120 AudioClock::set_mode (Mode m)
2121 {
2122         if (_mode == m) {
2123                 return;
2124         }
2125
2126         _mode = m;
2127
2128         insert_map.clear();
2129
2130         _layout->set_text ("");
2131
2132         if (_left_layout) {
2133
2134                 _left_layout->set_attributes (info_attributes);
2135                 _right_layout->set_attributes (info_attributes);
2136                 /* adjust info_height according to font size */
2137                 int ignored;
2138                 _left_layout->set_text (" 1234567890");
2139                 _left_layout->get_pixel_size (ignored, info_height);
2140
2141                 _left_layout->set_text ("");
2142                 _right_layout->set_text ("");
2143         }
2144
2145         switch (_mode) {
2146         case Timecode:
2147                 mode_based_info_ratio = 0.5;
2148                 insert_map.push_back (11);
2149                 insert_map.push_back (10);
2150                 insert_map.push_back (8);
2151                 insert_map.push_back (7);
2152                 insert_map.push_back (5);
2153                 insert_map.push_back (4);
2154                 insert_map.push_back (2);
2155                 insert_map.push_back (1);
2156                 break;
2157
2158         case BBT:
2159                 mode_based_info_ratio = 0.5;
2160                 insert_map.push_back (11);
2161                 insert_map.push_back (10);
2162                 insert_map.push_back (9);
2163                 insert_map.push_back (8);
2164                 insert_map.push_back (6);
2165                 insert_map.push_back (5);
2166                 insert_map.push_back (3);
2167                 insert_map.push_back (2);
2168                 insert_map.push_back (1);
2169                 break;
2170
2171         case MinSec:
2172                 mode_based_info_ratio = 0.5;
2173                 insert_map.push_back (12);
2174                 insert_map.push_back (11);
2175                 insert_map.push_back (10);
2176                 insert_map.push_back (8);
2177                 insert_map.push_back (7);
2178                 insert_map.push_back (5);
2179                 insert_map.push_back (4);
2180                 insert_map.push_back (2);
2181                 insert_map.push_back (1);
2182                 break;
2183
2184         case Frames:
2185                 mode_based_info_ratio = 0.5;
2186                 break;
2187         }
2188
2189         set (last_when, true);
2190
2191         if (!is_transient) {
2192                 ModeChanged (); /* EMIT SIGNAL (the static one)*/
2193         }
2194
2195         if (!_fixed_width) {
2196                 /* display is different, allow us to resize */
2197                 first_width = 0;
2198                 first_height = 0;
2199                 queue_resize ();
2200         }
2201
2202         mode_changed (); /* EMIT SIGNAL (the member one) */
2203 }
2204
2205 void
2206 AudioClock::set_bbt_reference (framepos_t pos)
2207 {
2208         bbt_reference_time = pos;
2209 }
2210
2211 void
2212 AudioClock::on_style_changed (const Glib::RefPtr<Gtk::Style>& old_style)
2213 {
2214         CairoWidget::on_style_changed (old_style);
2215         first_width = 0;
2216         first_height = 0;
2217         set_font ();
2218         set_colors ();
2219 }
2220
2221 void
2222 AudioClock::set_editable (bool yn)
2223 {
2224         editable = yn;
2225 }
2226
2227 void
2228 AudioClock::set_is_duration (bool yn)
2229 {
2230         if (yn == is_duration) {
2231                 return;
2232         }
2233
2234         is_duration = yn;
2235         set (last_when, true);
2236 }
2237
2238 void
2239 AudioClock::set_off (bool yn)
2240 {
2241         if (_off == yn) {
2242                 return;
2243         }
2244
2245         _off = yn;
2246
2247         /* force a redraw. last_when will be preserved, but the clock text will
2248          * change
2249          */
2250
2251         set (last_when, true);
2252 }
2253
2254 void
2255 AudioClock::focus ()
2256 {
2257         start_edit (Field (0));
2258 }
2259
2260 void
2261 AudioClock::set_corner_radius (double r)
2262 {
2263         corner_radius = r;
2264         first_width = 0;
2265         first_height = 0;
2266         queue_resize ();
2267 }
2268
2269 void
2270 AudioClock::set_fixed_width (bool yn)
2271 {
2272         _fixed_width = yn;
2273 }
2274
2275 void
2276 AudioClock::dpi_reset ()
2277 {
2278         /* force recomputation of size even if we are fixed width
2279          */
2280         first_width = 0;
2281         first_height = 0;
2282         queue_resize ();
2283 }
2284
2285 void
2286 AudioClock::set_negative_allowed (bool yn)
2287 {
2288         _negative_allowed = yn;
2289 }