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