0c7f41f6ebe699b4b48d43a9a631df8ef0753119
[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 lrint ((frames/(float)fps) * sr);
780
781         case 3:
782                 sscanf (str.c_str(), "%1" PRId32 "%" PRId32, &secs, &frames);
783                 return (secs * sr) + lrint ((frames/(float)fps) * sr);
784
785         case 4:
786                 sscanf (str.c_str(), "%2" PRId32 "%" PRId32, &secs, &frames);
787                 return (secs * sr) + lrint ((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) + lrint ((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) + lrint ((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) + lrint ((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) + lrint ((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::set_minsec (framepos_t when, bool /*force*/)
1104 {
1105         char buf[32];
1106         framecnt_t left;
1107         int hrs;
1108         int mins;
1109         int secs;
1110         int millisecs;
1111         bool negative = false;
1112
1113         if (_off) {
1114                 _layout->set_text (" --:--:--.---");
1115
1116                 if (_left_layout) {
1117                         _left_layout->set_text ("");
1118                         _right_layout->set_text ("");
1119                 }
1120
1121                 return;
1122         }
1123
1124         if (when < 0) {
1125                 when = -when;
1126                 negative = true;
1127         }
1128
1129         left = when;
1130         hrs = (int) floor (left / (_session->frame_rate() * 60.0f * 60.0f));
1131         left -= (framecnt_t) floor (hrs * _session->frame_rate() * 60.0f * 60.0f);
1132         mins = (int) floor (left / (_session->frame_rate() * 60.0f));
1133         left -= (framecnt_t) floor (mins * _session->frame_rate() * 60.0f);
1134         secs = (int) floor (left / (float) _session->frame_rate());
1135         left -= (framecnt_t) floor ((double)(secs * _session->frame_rate()));
1136         millisecs = floor (left * 1000.0 / (float) _session->frame_rate());
1137
1138         if (negative) {
1139                 snprintf (buf, sizeof (buf), "-%02" PRId32 ":%02" PRId32 ":%02" PRId32 ".%03" PRId32, hrs, mins, secs, millisecs);
1140         } else {
1141                 snprintf (buf, sizeof (buf), " %02" PRId32 ":%02" PRId32 ":%02" PRId32 ".%03" PRId32, hrs, mins, secs, millisecs);
1142         }
1143
1144         _layout->set_text (buf);
1145         set_slave_info();
1146 }
1147
1148 void
1149 AudioClock::set_timecode (framepos_t when, bool /*force*/)
1150 {
1151         Timecode::Time TC;
1152         bool negative = false;
1153
1154         if (_off) {
1155                 _layout->set_text (" --:--:--:--");
1156                 if (_left_layout) {
1157                         _left_layout->set_text ("");
1158                         _right_layout->set_text ("");
1159                 }
1160
1161                 return;
1162         }
1163
1164         if (when < 0) {
1165                 when = -when;
1166                 negative = true;
1167         }
1168
1169         if (is_duration) {
1170                 _session->timecode_duration (when, TC);
1171         } else {
1172                 _session->timecode_time (when, TC);
1173         }
1174
1175         TC.negative = TC.negative || negative;
1176
1177         _layout->set_text (Timecode::timecode_format_time(TC));
1178
1179         set_slave_info();
1180 }
1181
1182 void
1183 AudioClock::set_bbt (framepos_t when, bool /*force*/)
1184 {
1185         char buf[16];
1186         Timecode::BBT_Time BBT;
1187         bool negative = false;
1188
1189         if (_off) {
1190                 _layout->set_text (" ---|--|----");
1191                 if (_left_layout) {
1192                         _left_layout->set_text ("");
1193                         _right_layout->set_text ("");
1194                 }
1195                 return;
1196         }
1197
1198         if (when < 0) {
1199                 when = -when;
1200                 negative = true;
1201         }
1202
1203         /* handle a common case */
1204         if (is_duration) {
1205                 if (when == 0) {
1206                         BBT.bars = 0;
1207                         BBT.beats = 0;
1208                         BBT.ticks = 0;
1209                 } else {
1210                         _session->tempo_map().bbt_time (when, BBT);
1211                         BBT.bars--;
1212                         BBT.beats--;
1213                 }
1214         } else {
1215                 _session->tempo_map().bbt_time (when, BBT);
1216         }
1217
1218         if (negative) {
1219                 snprintf (buf, sizeof (buf), "-%03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
1220                           BBT.bars, BBT.beats, BBT.ticks);
1221         } else {
1222                 snprintf (buf, sizeof (buf), " %03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
1223                           BBT.bars, BBT.beats, BBT.ticks);
1224         }
1225
1226         _layout->set_text (buf);
1227
1228         if (_right_layout) {
1229                 framepos_t pos;
1230
1231                 if (bbt_reference_time < 0) {
1232                         pos = when;
1233                 } else {
1234                         pos = bbt_reference_time;
1235                 }
1236
1237                 TempoMetric m (_session->tempo_map().metric_at (pos));
1238
1239                 sprintf (buf, "%-5.1f", m.tempo().beats_per_minute());
1240                 _left_layout->set_markup (string_compose ("<span size=\"%1\">" TXTSPAN "%3</span> <span foreground=\"green\">%2</span></span>",
1241                                                           INFO_FONT_SIZE, buf, _("Tempo")));
1242
1243                 sprintf (buf, "%g/%g", m.meter().divisions_per_bar(), m.meter().note_divisor());
1244                 _right_layout->set_markup (string_compose ("<span size=\"%1\">" TXTSPAN "%3</span> <span foreground=\"green\">%2</span></span>",
1245                                                            INFO_FONT_SIZE, buf, _("Meter")));
1246         }
1247 }
1248
1249 void
1250 AudioClock::set_session (Session *s)
1251 {
1252         SessionHandlePtr::set_session (s);
1253
1254         if (_session) {
1255
1256                 _session->config.ParameterChanged.connect (_session_connections, invalidator (*this), boost::bind (&AudioClock::session_configuration_changed, this, _1), gui_context());
1257                 _session->tempo_map().PropertyChanged.connect (_session_connections, invalidator (*this), boost::bind (&AudioClock::session_property_changed, this, _1), gui_context());
1258
1259                 const XMLProperty* prop;
1260                 XMLNode* node = _session->extra_xml (X_("ClockModes"));
1261                 AudioClock::Mode amode;
1262
1263                 if (node) {
1264                         for (XMLNodeList::const_iterator i = node->children().begin(); i != node->children().end(); ++i) {
1265                                 if ((prop = (*i)->property (X_("name"))) && prop->value() == _name) {
1266
1267                                         if ((prop = (*i)->property (X_("mode"))) != 0) {
1268                                                 amode = AudioClock::Mode (string_2_enum (prop->value(), amode));
1269                                                 set_mode (amode);
1270                                         }
1271                                         if ((prop = (*i)->property (X_("on"))) != 0) {
1272                                                 set_off (!string_is_affirmative (prop->value()));
1273                                         }
1274                                         break;
1275                                 }
1276                         }
1277                 }
1278
1279                 set (last_when, true);
1280         }
1281 }
1282
1283 bool
1284 AudioClock::on_key_press_event (GdkEventKey* ev)
1285 {
1286         if (!editing) {
1287                 return false;
1288         }
1289
1290         string new_text;
1291         char new_char = 0;
1292         int highlight_length;
1293         framepos_t pos;
1294
1295         switch (ev->keyval) {
1296         case GDK_0:
1297         case GDK_KP_0:
1298                 new_char = '0';
1299                 break;
1300         case GDK_1:
1301         case GDK_KP_1:
1302                 new_char = '1';
1303                 break;
1304         case GDK_2:
1305         case GDK_KP_2:
1306                 new_char = '2';
1307                 break;
1308         case GDK_3:
1309         case GDK_KP_3:
1310                 new_char = '3';
1311                 break;
1312         case GDK_4:
1313         case GDK_KP_4:
1314                 new_char = '4';
1315                 break;
1316         case GDK_5:
1317         case GDK_KP_5:
1318                 new_char = '5';
1319                 break;
1320         case GDK_6:
1321         case GDK_KP_6:
1322                 new_char = '6';
1323                 break;
1324         case GDK_7:
1325         case GDK_KP_7:
1326                 new_char = '7';
1327                 break;
1328         case GDK_8:
1329         case GDK_KP_8:
1330                 new_char = '8';
1331                 break;
1332         case GDK_9:
1333         case GDK_KP_9:
1334                 new_char = '9';
1335                 break;
1336
1337         case GDK_minus:
1338         case GDK_KP_Subtract:
1339                 if (_negative_allowed && input_string.empty()) {
1340                                 edit_is_negative = true;
1341                                 edit_string.replace(0,1,"-");
1342                                 _layout->set_text (edit_string);
1343                                 queue_draw ();
1344                 } else {
1345                         end_edit_relative (false);
1346                 }
1347                 return true;
1348                 break;
1349
1350         case GDK_plus:
1351                 end_edit_relative (true);
1352                 return true;
1353                 break;
1354
1355         case GDK_Tab:
1356         case GDK_Return:
1357         case GDK_KP_Enter:
1358                 end_edit (true);
1359                 return true;
1360                 break;
1361
1362         case GDK_Escape:
1363                 end_edit (false);
1364                 ChangeAborted();  /*  EMIT SIGNAL  */
1365                 return true;
1366
1367         case GDK_Delete:
1368         case GDK_BackSpace:
1369                 if (!input_string.empty()) {
1370                         /* delete the last key entered
1371                         */
1372                         input_string = input_string.substr (0, input_string.length() - 1);
1373                 }
1374                 goto use_input_string;
1375
1376         default:
1377                 return false;
1378         }
1379
1380         if (!insert_map.empty() && (input_string.length() >= insert_map.size())) {
1381                 /* too many digits: eat the key event, but do nothing with it */
1382                 return true;
1383         }
1384
1385         input_string.push_back (new_char);
1386
1387   use_input_string:
1388
1389         switch (_mode) {
1390         case Frames:
1391                 /* get this one in the right order, and to the right width */
1392                 if (ev->keyval == GDK_Delete || ev->keyval == GDK_BackSpace) {
1393                         edit_string = edit_string.substr (0, edit_string.length() - 1);
1394                 } else {
1395                         edit_string.push_back (new_char);
1396                 }
1397                 if (!edit_string.empty()) {
1398                         char buf[32];
1399                         sscanf (edit_string.c_str(), "%" PRId64, &pos);
1400                         snprintf (buf, sizeof (buf), " %10" PRId64, pos);
1401                         edit_string = buf;
1402                 }
1403                 /* highlight the whole thing */
1404                 highlight_length = edit_string.length();
1405                 break;
1406
1407         default:
1408                 highlight_length = merge_input_and_edit_string ();
1409         }
1410
1411         if (edit_is_negative) {
1412                 edit_string.replace(0,1,"-");
1413         } else {
1414                 if (!pre_edit_string.empty() && (pre_edit_string.at(0) == '-')) {
1415                         edit_string.replace(0,1,"_");
1416                 } else {
1417                         edit_string.replace(0,1," ");
1418                 }
1419         }
1420
1421         show_edit_status (highlight_length);
1422         _layout->set_text (edit_string);
1423         queue_draw ();
1424
1425         return true;
1426 }
1427
1428 int
1429 AudioClock::merge_input_and_edit_string ()
1430 {
1431         /* merge with pre-edit-string into edit string */
1432
1433         edit_string = pre_edit_string;
1434
1435         if (input_string.empty()) {
1436                 return 0;
1437         }
1438
1439         string::size_type target;
1440         for (string::size_type i = 0; i < input_string.length(); ++i) {
1441                 target = insert_map[input_string.length() - 1 - i];
1442                 edit_string[target] = input_string[i];
1443         }
1444         /* highlight from end to wherever the last character was added */
1445         return edit_string.length() - insert_map[input_string.length()-1];
1446 }
1447
1448
1449 bool
1450 AudioClock::on_key_release_event (GdkEventKey *ev)
1451 {
1452         if (!editing) {
1453                 return false;
1454         }
1455
1456         /* return true for keys that we used on press
1457            so that they cannot possibly do double-duty
1458         */
1459         switch (ev->keyval) {
1460         case GDK_0:
1461         case GDK_KP_0:
1462         case GDK_1:
1463         case GDK_KP_1:
1464         case GDK_2:
1465         case GDK_KP_2:
1466         case GDK_3:
1467         case GDK_KP_3:
1468         case GDK_4:
1469         case GDK_KP_4:
1470         case GDK_5:
1471         case GDK_KP_5:
1472         case GDK_6:
1473         case GDK_KP_6:
1474         case GDK_7:
1475         case GDK_KP_7:
1476         case GDK_8:
1477         case GDK_KP_8:
1478         case GDK_9:
1479         case GDK_KP_9:
1480         case GDK_period:
1481         case GDK_comma:
1482         case GDK_KP_Decimal:
1483         case GDK_Tab:
1484         case GDK_Return:
1485         case GDK_KP_Enter:
1486         case GDK_Escape:
1487         case GDK_minus:
1488         case GDK_plus:
1489         case GDK_KP_Add:
1490         case GDK_KP_Subtract:
1491                 return true;
1492         default:
1493                 return false;
1494         }
1495 }
1496
1497 AudioClock::Field
1498 AudioClock::index_to_field (int index) const
1499 {
1500         switch (_mode) {
1501         case Timecode:
1502                 if (index < 4) {
1503                         return Timecode_Hours;
1504                 } else if (index < 7) {
1505                         return Timecode_Minutes;
1506                 } else if (index < 10) {
1507                         return Timecode_Seconds;
1508                 } else {
1509                         return Timecode_Frames;
1510                 }
1511                 break;
1512         case BBT:
1513                 if (index < 5) {
1514                         return Bars;
1515                 } else if (index < 7) {
1516                         return Beats;
1517                 } else {
1518                         return Ticks;
1519                 }
1520                 break;
1521         case MinSec:
1522                 if (index < 3) {
1523                         return Timecode_Hours;
1524                 } else if (index < 6) {
1525                         return MS_Minutes;
1526                 } else if (index < 9) {
1527                         return MS_Seconds;
1528                 } else {
1529                         return MS_Milliseconds;
1530                 }
1531                 break;
1532         case Frames:
1533                 return AudioFrames;
1534                 break;
1535         }
1536
1537         return Field (0);
1538 }
1539
1540 bool
1541 AudioClock::on_button_press_event (GdkEventButton *ev)
1542 {
1543         switch (ev->button) {
1544         case 1:
1545                 if (editable && !_off) {
1546                         int index;
1547                         int trailing;
1548                         int y;
1549                         int x;
1550
1551                         /* the text has been centered vertically, so adjust
1552                          * x and y.
1553                          */
1554                         int xcenter = (get_width() - layout_width) /2;
1555
1556                         y = ev->y - ((upper_height - layout_height)/2);
1557                         x = ev->x - xcenter;
1558
1559                         if (!_layout->xy_to_index (x * PANGO_SCALE, y * PANGO_SCALE, index, trailing)) {
1560                                 /* pretend it is a character on the far right */
1561                                 index = 99;
1562                         }
1563                         drag_field = index_to_field (index);
1564                         dragging = true;
1565                         /* make absolutely sure that the pointer is grabbed */
1566                         gdk_pointer_grab(ev->window,false ,
1567                                          GdkEventMask( Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_PRESS_MASK |Gdk::BUTTON_RELEASE_MASK),
1568                                          NULL,NULL,ev->time);
1569                         drag_accum = 0;
1570                         drag_start_y = ev->y;
1571                         drag_y = ev->y;
1572                 }
1573                 break;
1574
1575         default:
1576                 return false;
1577                 break;
1578         }
1579
1580         return true;
1581 }
1582
1583 bool
1584 AudioClock::on_button_release_event (GdkEventButton *ev)
1585 {
1586         if (editable && !_off) {
1587                 if (dragging) {
1588                         gdk_pointer_ungrab (GDK_CURRENT_TIME);
1589                         dragging = false;
1590                         if (ev->y > drag_start_y+1 || ev->y < drag_start_y-1 || Keyboard::modifier_state_equals (ev->state, Keyboard::TertiaryModifier)){
1591                                 // we actually dragged so return without
1592                                 // setting editing focus, or we shift clicked
1593                                 return true;
1594                         } else {
1595                                 if (ev->button == 1) {
1596
1597                                         if (_edit_by_click_field) {
1598
1599                                                 int xcenter = (get_width() - layout_width) /2;
1600                                                 int index = 0;
1601                                                 int trailing;
1602                                                 int y = ev->y - ((upper_height - layout_height)/2);
1603                                                 int x = ev->x - xcenter;
1604                                                 Field f;
1605
1606                                                 if (!_layout->xy_to_index (x * PANGO_SCALE, y * PANGO_SCALE, index, trailing)) {
1607                                                         return true;
1608                                                 }
1609
1610                                                 f = index_to_field (index);
1611
1612                                                 switch (f) {
1613                                                 case Timecode_Frames:
1614                                                 case MS_Milliseconds:
1615                                                 case Ticks:
1616                                                         f = Field (0);
1617                                                         break;
1618                                                 default:
1619                                                         break;
1620                                                 }
1621                                                 start_edit (f);
1622                                         } else {
1623                                                 start_edit ();
1624                                         }
1625                                 }
1626                         }
1627                 }
1628         }
1629
1630         if (Keyboard::is_context_menu_event (ev)) {
1631                 if (ops_menu == 0) {
1632                         build_ops_menu ();
1633                 }
1634                 ops_menu->popup (1, ev->time);
1635                 return true;
1636         }
1637
1638         return false;
1639 }
1640
1641 bool
1642 AudioClock::on_focus_out_event (GdkEventFocus* ev)
1643 {
1644         bool ret = CairoWidget::on_focus_out_event (ev);
1645
1646         if (editing) {
1647                 end_edit (false);
1648         }
1649
1650         return ret;
1651 }
1652
1653 bool
1654 AudioClock::on_scroll_event (GdkEventScroll *ev)
1655 {
1656         int index;
1657         int trailing;
1658
1659         if (editing || _session == 0 || !editable || _off) {
1660                 return false;
1661         }
1662
1663         int y;
1664         int x;
1665
1666         /* the text has been centered vertically, so adjust
1667          * x and y.
1668          */
1669
1670         int xcenter = (get_width() - layout_width) /2;
1671         y = ev->y - ((upper_height - layout_height)/2);
1672         x = ev->x - xcenter;
1673
1674         if (!_layout->xy_to_index (x * PANGO_SCALE, y * PANGO_SCALE, index, trailing)) {
1675                 /* not in the main layout */
1676                 return false;
1677         }
1678
1679         Field f = index_to_field (index);
1680         framepos_t frames = 0;
1681
1682         switch (ev->direction) {
1683
1684         case GDK_SCROLL_UP:
1685                 frames = get_frame_step (f);
1686                 if (frames != 0) {
1687                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
1688                                 frames *= 10;
1689                         }
1690                         set (current_time() + frames, true);
1691                         ValueChanged (); /* EMIT_SIGNAL */
1692                 }
1693                 break;
1694
1695         case GDK_SCROLL_DOWN:
1696                 frames = get_frame_step (f);
1697                 if (frames != 0) {
1698                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
1699                                 frames *= 10;
1700                         }
1701
1702                         if (!_negative_allowed && (double)current_time() - (double)frames < 0.0) {
1703                                 set (0, true);
1704                         } else {
1705                                 set (current_time() - frames, true);
1706                         }
1707
1708                         ValueChanged (); /* EMIT_SIGNAL */
1709                 }
1710                 break;
1711
1712         default:
1713                 return false;
1714                 break;
1715         }
1716
1717         return true;
1718 }
1719
1720 bool
1721 AudioClock::on_motion_notify_event (GdkEventMotion *ev)
1722 {
1723         if (editing || _session == 0 || !dragging) {
1724                 return false;
1725         }
1726
1727         float pixel_frame_scale_factor = 0.2f;
1728
1729         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier))  {
1730                 pixel_frame_scale_factor = 0.1f;
1731         }
1732
1733
1734         if (Keyboard::modifier_state_contains (ev->state,
1735                                                Keyboard::PrimaryModifier|Keyboard::SecondaryModifier)) {
1736
1737                 pixel_frame_scale_factor = 0.025f;
1738         }
1739
1740         double y_delta = ev->y - drag_y;
1741
1742         drag_accum +=  y_delta*pixel_frame_scale_factor;
1743
1744         drag_y = ev->y;
1745
1746         if (floor (drag_accum) != 0) {
1747
1748                 framepos_t frames;
1749                 framepos_t pos;
1750                 int dir;
1751                 dir = (drag_accum < 0 ? 1:-1);
1752                 pos = current_time();
1753                 frames = get_frame_step (drag_field, pos, dir);
1754
1755                 if (frames  != 0 &&  frames * drag_accum < current_time()) {
1756                         set ((framepos_t) floor (pos - drag_accum * frames), false); // minus because up is negative in GTK
1757                 } else {
1758                         set (0 , false);
1759                 }
1760
1761                 drag_accum= 0;
1762                 ValueChanged();  /* EMIT_SIGNAL */
1763         }
1764
1765         return true;
1766 }
1767
1768 framepos_t
1769 AudioClock::get_frame_step (Field field, framepos_t pos, int dir)
1770 {
1771         framecnt_t f = 0;
1772         Timecode::BBT_Time BBT;
1773         switch (field) {
1774         case Timecode_Hours:
1775                 f = (framecnt_t) floor (3600.0 * _session->frame_rate());
1776                 break;
1777         case Timecode_Minutes:
1778                 f = (framecnt_t) floor (60.0 * _session->frame_rate());
1779                 break;
1780         case Timecode_Seconds:
1781                 f = _session->frame_rate();
1782                 break;
1783         case Timecode_Frames:
1784                 f = (framecnt_t) floor (_session->frame_rate() / _session->timecode_frames_per_second());
1785                 break;
1786
1787         case AudioFrames:
1788                 f = 1;
1789                 break;
1790
1791         case MS_Hours:
1792                 f = (framecnt_t) floor (3600.0 * _session->frame_rate());
1793                 break;
1794         case MS_Minutes:
1795                 f = (framecnt_t) floor (60.0 * _session->frame_rate());
1796                 break;
1797         case MS_Seconds:
1798                 f = (framecnt_t) _session->frame_rate();
1799                 break;
1800         case MS_Milliseconds:
1801                 f = (framecnt_t) floor (_session->frame_rate() / 1000.0);
1802                 break;
1803
1804         case Bars:
1805                 BBT.bars = 1;
1806                 BBT.beats = 0;
1807                 BBT.ticks = 0;
1808                 f = _session->tempo_map().bbt_duration_at (pos,BBT,dir);
1809                 break;
1810         case Beats:
1811                 BBT.bars = 0;
1812                 BBT.beats = 1;
1813                 BBT.ticks = 0;
1814                 f = _session->tempo_map().bbt_duration_at(pos,BBT,dir);
1815                 break;
1816         case Ticks:
1817                 BBT.bars = 0;
1818                 BBT.beats = 0;
1819                 BBT.ticks = 1;
1820                 f = _session->tempo_map().bbt_duration_at(pos,BBT,dir);
1821                 break;
1822         default:
1823                 error << string_compose (_("programming error: %1"), "attempt to get frames from non-text field!") << endmsg;
1824                 f = 0;
1825                 break;
1826         }
1827
1828         return f;
1829 }
1830
1831 framepos_t
1832 AudioClock::current_time (framepos_t) const
1833 {
1834         return last_when;
1835 }
1836
1837 framepos_t
1838 AudioClock::current_duration (framepos_t pos) const
1839 {
1840         framepos_t ret = 0;
1841
1842         switch (_mode) {
1843         case Timecode:
1844                 ret = last_when;
1845                 break;
1846         case BBT:
1847                 ret = frame_duration_from_bbt_string (pos, _layout->get_text());
1848                 break;
1849
1850         case MinSec:
1851                 ret = last_when;
1852                 break;
1853
1854         case Frames:
1855                 ret = last_when;
1856                 break;
1857         }
1858
1859         return ret;
1860 }
1861
1862 bool
1863 AudioClock::bbt_validate_edit (const string& str)
1864 {
1865         AnyTime any;
1866
1867         if (sscanf (str.c_str(), BBT_SCANF_FORMAT, &any.bbt.bars, &any.bbt.beats, &any.bbt.ticks) != 3) {
1868                 return false;
1869         }
1870
1871         if (any.bbt.ticks > Timecode::BBT_Time::ticks_per_beat) {
1872                 return false;
1873         }
1874
1875         if (!is_duration && any.bbt.bars == 0) {
1876                 return false;
1877         }
1878
1879         if (!is_duration && any.bbt.beats == 0) {
1880                 return false;
1881         }
1882
1883         return true;
1884 }
1885
1886 bool
1887 AudioClock::timecode_validate_edit (const string&)
1888 {
1889         Timecode::Time TC;
1890         int hours;
1891         char ignored[2];
1892
1893         if (sscanf (_layout->get_text().c_str(), "%[- _]%" PRId32 ":%" PRId32 ":%" PRId32 "%[:;]%" PRId32,
1894                     ignored, &hours, &TC.minutes, &TC.seconds, ignored, &TC.frames) != 6) {
1895                 return false;
1896         }
1897
1898         if (hours < 0) {
1899                 TC.hours = hours * -1;
1900                 TC.negative = true;
1901         } else {
1902                 TC.hours = hours;
1903                 TC.negative = false;
1904         }
1905
1906         if (TC.negative && !_negative_allowed) {
1907                 return false;
1908         }
1909
1910         if (TC.hours > 23U || TC.minutes > 59U || TC.seconds > 59U) {
1911                 return false;
1912         }
1913
1914         if (TC.frames > (uint32_t) rint (_session->timecode_frames_per_second()) - 1) {
1915                 return false;
1916         }
1917
1918         if (_session->timecode_drop_frames()) {
1919                 if (TC.minutes % 10 && TC.seconds == 0U && TC.frames < 2U) {
1920                         return false;
1921                 }
1922         }
1923
1924         return true;
1925 }
1926
1927 bool
1928 AudioClock::minsec_validate_edit (const string& str)
1929 {
1930         int hrs, mins, secs, millisecs;
1931
1932         if (sscanf (str.c_str(), "%d:%d:%d.%d", &hrs, &mins, &secs, &millisecs) != 4) {
1933                 return false;
1934         }
1935
1936         if (hrs > 23 || mins > 59 || secs > 59 || millisecs > 999) {
1937                 return false;
1938         }
1939
1940         return true;
1941 }
1942
1943 framepos_t
1944 AudioClock::frames_from_timecode_string (const string& str) const
1945 {
1946         if (_session == 0) {
1947                 return 0;
1948         }
1949
1950         Timecode::Time TC;
1951         framepos_t sample;
1952         char ignored[2];
1953         int hours;
1954
1955         if (sscanf (str.c_str(), "%[- _]%d:%d:%d%[:;]%d", ignored, &hours, &TC.minutes, &TC.seconds, ignored, &TC.frames) != 6) {
1956                 error << string_compose (_("programming error: %1 %2"), "badly formatted timecode clock string", str) << endmsg;
1957                 return 0;
1958         }
1959         TC.hours = abs(hours);
1960         TC.rate = _session->timecode_frames_per_second();
1961         TC.drop= _session->timecode_drop_frames();
1962
1963         _session->timecode_to_sample (TC, sample, false /* use_offset */, false /* use_subframes */ );
1964
1965         // timecode_tester ();
1966         if (edit_is_negative) {
1967                 sample = - sample;
1968         }
1969
1970         return sample;
1971 }
1972
1973 framepos_t
1974 AudioClock::frames_from_minsec_string (const string& str) const
1975 {
1976         if (_session == 0) {
1977                 return 0;
1978         }
1979
1980         int hrs, mins, secs, millisecs;
1981         framecnt_t sr = _session->frame_rate();
1982
1983         if (sscanf (str.c_str(), "%d:%d:%d.%d", &hrs, &mins, &secs, &millisecs) != 4) {
1984                 error << string_compose (_("programming error: %1 %2"), "badly formatted minsec clock string", str) << endmsg;
1985                 return 0;
1986         }
1987
1988         return (framepos_t) floor ((hrs * 60.0f * 60.0f * sr) + (mins * 60.0f * sr) + (secs * sr) + (millisecs * sr / 1000.0));
1989 }
1990
1991 framepos_t
1992 AudioClock::frames_from_bbt_string (framepos_t pos, const string& str) const
1993 {
1994         if (_session == 0) {
1995                 error << "AudioClock::current_time() called with BBT mode but without session!" << endmsg;
1996                 return 0;
1997         }
1998
1999         AnyTime any;
2000         any.type = AnyTime::BBT;
2001
2002         if (sscanf (str.c_str(), BBT_SCANF_FORMAT, &any.bbt.bars, &any.bbt.beats, &any.bbt.ticks) != 3) {
2003                 return 0;
2004         }
2005
2006         if (is_duration) {
2007                 any.bbt.bars++;
2008                 any.bbt.beats++;
2009                 return _session->any_duration_to_frames (pos, any);
2010         } else {
2011                 return _session->convert_to_frames (any);
2012         }
2013 }
2014
2015
2016 framepos_t
2017 AudioClock::frame_duration_from_bbt_string (framepos_t pos, const string& str) const
2018 {
2019         if (_session == 0) {
2020                 error << "AudioClock::frame_duration_from_bbt_string() called with BBT mode but without session!" << endmsg;
2021                 return 0;
2022         }
2023
2024         Timecode::BBT_Time bbt;
2025
2026         if (sscanf (str.c_str(), BBT_SCANF_FORMAT, &bbt.bars, &bbt.beats, &bbt.ticks) != 3) {
2027                 return 0;
2028         }
2029
2030         return _session->tempo_map().bbt_duration_at(pos,bbt,1);
2031 }
2032
2033 framepos_t
2034 AudioClock::frames_from_audioframes_string (const string& str) const
2035 {
2036         framepos_t f;
2037         sscanf (str.c_str(), "%" PRId64, &f);
2038         return f;
2039 }
2040
2041 void
2042 AudioClock::build_ops_menu ()
2043 {
2044         using namespace Menu_Helpers;
2045         ops_menu = new Menu;
2046         MenuList& ops_items = ops_menu->items();
2047         ops_menu->set_name ("ArdourContextMenu");
2048
2049         if (!Profile->get_sae()) {
2050                 ops_items.push_back (MenuElem (_("Timecode"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), Timecode)));
2051         }
2052         ops_items.push_back (MenuElem (_("Bars:Beats"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), BBT)));
2053         ops_items.push_back (MenuElem (_("Minutes:Seconds"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), MinSec)));
2054         ops_items.push_back (MenuElem (_("Samples"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), Frames)));
2055
2056         if (editable && !_off && !is_duration && !_follows_playhead) {
2057                 ops_items.push_back (SeparatorElem());
2058                 ops_items.push_back (MenuElem (_("Set From Playhead"), sigc::mem_fun(*this, &AudioClock::set_from_playhead)));
2059                 ops_items.push_back (MenuElem (_("Locate to This Time"), sigc::mem_fun(*this, &AudioClock::locate)));
2060         }
2061 }
2062
2063 void
2064 AudioClock::set_from_playhead ()
2065 {
2066         if (!_session) {
2067                 return;
2068         }
2069
2070         set (_session->transport_frame());
2071         ValueChanged ();
2072 }
2073
2074 void
2075 AudioClock::locate ()
2076 {
2077         if (!_session || is_duration) {
2078                 return;
2079         }
2080
2081         _session->request_locate (current_time(), _session->transport_rolling ());
2082 }
2083
2084 void
2085 AudioClock::set_mode (Mode m)
2086 {
2087         if (_mode == m) {
2088                 return;
2089         }
2090
2091         _mode = m;
2092
2093         insert_map.clear();
2094
2095         _layout->set_text ("");
2096
2097         if (_left_layout) {
2098
2099                 _left_layout->set_attributes (info_attributes);
2100                 _right_layout->set_attributes (info_attributes);
2101                 /* adjust info_height according to font size */
2102                 int ignored;
2103                 _left_layout->set_text (" 1234567890");
2104                 _left_layout->get_pixel_size (ignored, info_height);
2105
2106                 _left_layout->set_text ("");
2107                 _right_layout->set_text ("");
2108         }
2109
2110         switch (_mode) {
2111         case Timecode:
2112                 mode_based_info_ratio = 0.6;
2113                 insert_map.push_back (11);
2114                 insert_map.push_back (10);
2115                 insert_map.push_back (8);
2116                 insert_map.push_back (7);
2117                 insert_map.push_back (5);
2118                 insert_map.push_back (4);
2119                 insert_map.push_back (2);
2120                 insert_map.push_back (1);
2121                 break;
2122
2123         case BBT:
2124                 mode_based_info_ratio = 0.5;
2125                 insert_map.push_back (11);
2126                 insert_map.push_back (10);
2127                 insert_map.push_back (9);
2128                 insert_map.push_back (8);
2129                 insert_map.push_back (6);
2130                 insert_map.push_back (5);
2131                 insert_map.push_back (3);
2132                 insert_map.push_back (2);
2133                 insert_map.push_back (1);
2134                 break;
2135
2136         case MinSec:
2137                 mode_based_info_ratio = 0.6;
2138                 insert_map.push_back (12);
2139                 insert_map.push_back (11);
2140                 insert_map.push_back (10);
2141                 insert_map.push_back (8);
2142                 insert_map.push_back (7);
2143                 insert_map.push_back (5);
2144                 insert_map.push_back (4);
2145                 insert_map.push_back (2);
2146                 insert_map.push_back (1);
2147                 break;
2148
2149         case Frames:
2150                 mode_based_info_ratio = 0.45;
2151                 break;
2152         }
2153
2154         set (last_when, true);
2155
2156         if (!is_transient) {
2157                 ModeChanged (); /* EMIT SIGNAL (the static one)*/
2158         }
2159
2160         mode_changed (); /* EMIT SIGNAL (the member one) */
2161 }
2162
2163 void
2164 AudioClock::set_bbt_reference (framepos_t pos)
2165 {
2166         bbt_reference_time = pos;
2167 }
2168
2169 void
2170 AudioClock::on_style_changed (const Glib::RefPtr<Gtk::Style>& old_style)
2171 {
2172         CairoWidget::on_style_changed (old_style);
2173
2174         Gtk::Requisition req;
2175         set_clock_dimensions (req);
2176
2177         set_font ();
2178         set_colors ();
2179 }
2180
2181 void
2182 AudioClock::set_editable (bool yn)
2183 {
2184         editable = yn;
2185 }
2186
2187 void
2188 AudioClock::set_is_duration (bool yn)
2189 {
2190         if (yn == is_duration) {
2191                 return;
2192         }
2193
2194         is_duration = yn;
2195         set (last_when, true);
2196 }
2197
2198 void
2199 AudioClock::set_off (bool yn)
2200 {
2201         if (_off == yn) {
2202                 return;
2203         }
2204
2205         _off = yn;
2206
2207         /* force a redraw. last_when will be preserved, but the clock text will
2208          * change
2209          */
2210
2211         set (last_when, true);
2212 }
2213
2214 void
2215 AudioClock::focus ()
2216 {
2217         start_edit (Field (0));
2218 }
2219
2220 void
2221 AudioClock::set_corner_radius (double r)
2222 {
2223         corner_radius = r;
2224         first_width = 0;
2225         first_height = 0;
2226         queue_resize ();
2227 }
2228
2229 void
2230 AudioClock::dpi_reset ()
2231 {
2232         /* force recomputation of size even if we are fixed width
2233          */
2234         first_width = 0;
2235         first_height = 0;
2236         queue_resize ();
2237 }
2238
2239 void
2240 AudioClock::set_negative_allowed (bool yn)
2241 {
2242         _negative_allowed = yn;
2243 }