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