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