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