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