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