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