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