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