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