03a7ca33bac00eef3050014214a4915fee49a2a3
[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 (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                         case LTC:
1097                                 _left_layout->set_text ("LTC");
1098                                 break;
1099                         }
1100                 } else {
1101                         _left_layout->set_text ("INT");
1102                 }
1103
1104                 _right_layout->set_text ("TBDiscussed");
1105         }
1106 }
1107
1108 void
1109 AudioClock::set_bbt (framepos_t when, bool /*force*/)
1110 {
1111         char buf[16];
1112         Timecode::BBT_Time BBT;
1113         bool negative = false;
1114
1115         if (_off) {
1116                 _layout->set_text ("\u2012\u2012\u2012|\u2012\u2012|\u2012\u2012\u2012\u2012");
1117                 if (_left_layout) {
1118                         _left_layout->set_text ("");
1119                         _right_layout->set_text ("");
1120                 }
1121                 return;
1122         }
1123
1124         if (when < 0) {
1125                 when = -when;
1126                 negative = true;
1127         }
1128
1129         /* handle a common case */
1130         if (is_duration) {
1131                 if (when == 0) {
1132                         BBT.bars = 0;
1133                         BBT.beats = 0;
1134                         BBT.ticks = 0;
1135                 } else {
1136                         _session->tempo_map().bbt_time (when, BBT);
1137                         BBT.bars--;
1138                         BBT.beats--;
1139                 }
1140         } else {
1141                 _session->tempo_map().bbt_time (when, BBT);
1142         }
1143
1144         if (negative) {
1145                 snprintf (buf, sizeof (buf), "-%03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32, 
1146                           BBT.bars, BBT.beats, BBT.ticks);
1147         } else {
1148                 snprintf (buf, sizeof (buf), " %03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32, 
1149                           BBT.bars, BBT.beats, BBT.ticks);
1150         }
1151
1152         _layout->set_text (buf);
1153                  
1154         if (_right_layout) {
1155                 framepos_t pos;
1156
1157                 if (bbt_reference_time < 0) {
1158                         pos = when;
1159                 } else {
1160                         pos = bbt_reference_time;
1161                 }
1162
1163                 TempoMetric m (_session->tempo_map().metric_at (pos));
1164
1165                 sprintf (buf, "%-5.2f", m.tempo().beats_per_minute());
1166                 _left_layout->set_text (buf);
1167
1168                 sprintf (buf, "%g/%g", m.meter().divisions_per_bar(), m.meter().note_divisor());
1169                 _right_layout->set_text (buf);
1170         }
1171 }
1172
1173 void
1174 AudioClock::set_session (Session *s)
1175 {
1176         SessionHandlePtr::set_session (s);
1177
1178         if (_session) {
1179
1180                 _session->config.ParameterChanged.connect (_session_connections, invalidator (*this), boost::bind (&AudioClock::session_configuration_changed, this, _1), gui_context());
1181
1182                 const XMLProperty* prop;
1183                 XMLNode* node = _session->extra_xml (X_("ClockModes"));
1184                 AudioClock::Mode amode;
1185
1186                 if (node) {
1187                         for (XMLNodeList::const_iterator i = node->children().begin(); i != node->children().end(); ++i) {
1188                                 if ((prop = (*i)->property (X_("name"))) && prop->value() == _name) {
1189
1190                                         if ((prop = (*i)->property (X_("mode"))) != 0) {
1191                                                 amode = AudioClock::Mode (string_2_enum (prop->value(), amode));
1192                                                 set_mode (amode);
1193                                         }
1194                                         if ((prop = (*i)->property (X_("on"))) != 0) {
1195                                                 set_off (!string_is_affirmative (prop->value()));
1196                                         }
1197                                         break;
1198                                 }
1199                         }
1200                 }
1201
1202                 set (last_when, true);
1203         }
1204 }
1205
1206 bool
1207 AudioClock::on_key_press_event (GdkEventKey* ev)
1208 {
1209         if (!editing) {
1210                 return false;
1211         }
1212
1213         string new_text;
1214         char new_char = 0;
1215         int highlight_length;
1216         framepos_t pos;
1217
1218         switch (ev->keyval) {
1219         case GDK_0:
1220         case GDK_KP_0:
1221                 new_char = '0';
1222                 break;
1223         case GDK_1:
1224         case GDK_KP_1:
1225                 new_char = '1';
1226                 break;
1227         case GDK_2:
1228         case GDK_KP_2:
1229                 new_char = '2';
1230                 break;
1231         case GDK_3:
1232         case GDK_KP_3:
1233                 new_char = '3';
1234                 break;
1235         case GDK_4:
1236         case GDK_KP_4:
1237                 new_char = '4';
1238                 break;
1239         case GDK_5:
1240         case GDK_KP_5:
1241                 new_char = '5';
1242                 break;
1243         case GDK_6:
1244         case GDK_KP_6:
1245                 new_char = '6';
1246                 break;
1247         case GDK_7:
1248         case GDK_KP_7:
1249                 new_char = '7';
1250                 break;
1251         case GDK_8:
1252         case GDK_KP_8:
1253                 new_char = '8';
1254                 break;
1255         case GDK_9:
1256         case GDK_KP_9:
1257                 new_char = '9';
1258                 break;
1259
1260         case GDK_minus:
1261         case GDK_KP_Subtract:
1262                 end_edit_relative (false);
1263                 return true;
1264                 break;
1265
1266         case GDK_plus:
1267         case GDK_KP_Add:
1268                 end_edit_relative (true);
1269                 return true;
1270                 break;
1271
1272         case GDK_Tab:
1273         case GDK_Return:
1274         case GDK_KP_Enter:
1275                 end_edit (true);
1276                 return true;
1277                 break;
1278
1279         case GDK_Escape:
1280                 end_edit (false);
1281                 ChangeAborted();  /*  EMIT SIGNAL  */
1282                 return true;
1283
1284         case GDK_Delete:
1285         case GDK_BackSpace:
1286                 if (!input_string.empty()) {
1287                         /* delete the last key entered
1288                         */
1289                         input_string = input_string.substr (0, input_string.length() - 1);
1290                 }
1291                 goto use_input_string;
1292
1293         default:
1294                 return false;
1295         }
1296
1297         if (!insert_map.empty() && (input_string.length() >= insert_map.size())) {
1298                 /* too many digits: eat the key event, but do nothing with it */
1299                 return true;
1300         }
1301
1302         input_string.push_back (new_char);
1303
1304   use_input_string:
1305
1306         switch (_mode) {
1307         case Frames:
1308                 /* get this one in the right order, and to the right width */
1309                 if (ev->keyval == GDK_Delete || ev->keyval == GDK_BackSpace) {
1310                         edit_string = edit_string.substr (0, edit_string.length() - 1);
1311                 } else {
1312                         edit_string.push_back (new_char);
1313                 }
1314                 if (!edit_string.empty()) {
1315                         char buf[32];
1316                         sscanf (edit_string.c_str(), "%" PRId64, &pos);
1317                         snprintf (buf, sizeof (buf), " %10" PRId64, pos);
1318                         edit_string = buf;
1319                 }
1320                 /* highlight the whole thing */
1321                 highlight_length = edit_string.length();
1322                 break;
1323
1324         default:
1325                 highlight_length = merge_input_and_edit_string ();
1326         }
1327
1328         show_edit_status (highlight_length);
1329         _layout->set_text (edit_string);
1330         queue_draw ();
1331
1332         return true;
1333 }
1334
1335 int
1336 AudioClock::merge_input_and_edit_string ()
1337 {
1338         /* merge with pre-edit-string into edit string */
1339         
1340         edit_string = pre_edit_string;
1341         
1342         if (input_string.empty()) {
1343                 return 0;
1344         } 
1345
1346         string::size_type target;
1347         for (string::size_type i = 0; i < input_string.length(); ++i) {
1348                 target = insert_map[input_string.length() - 1 - i];
1349                 edit_string[target] = input_string[i];
1350         }
1351         /* highlight from end to wherever the last character was added */
1352         return edit_string.length() - insert_map[input_string.length()-1];
1353 }
1354
1355
1356 bool
1357 AudioClock::on_key_release_event (GdkEventKey *ev)
1358 {
1359         if (!editing) {
1360                 return false;
1361         }
1362         
1363         /* return true for keys that we used on press
1364            so that they cannot possibly do double-duty
1365         */
1366         switch (ev->keyval) {
1367         case GDK_0:
1368         case GDK_KP_0:
1369         case GDK_1:
1370         case GDK_KP_1:
1371         case GDK_2:
1372         case GDK_KP_2:
1373         case GDK_3:
1374         case GDK_KP_3:
1375         case GDK_4:
1376         case GDK_KP_4:
1377         case GDK_5:
1378         case GDK_KP_5:
1379         case GDK_6:
1380         case GDK_KP_6:
1381         case GDK_7:
1382         case GDK_KP_7:
1383         case GDK_8:
1384         case GDK_KP_8:
1385         case GDK_9:
1386         case GDK_KP_9:
1387         case GDK_period:
1388         case GDK_comma:
1389         case GDK_KP_Decimal:
1390         case GDK_Tab:
1391         case GDK_Return:
1392         case GDK_KP_Enter:
1393         case GDK_Escape:
1394         case GDK_minus:
1395         case GDK_plus:
1396         case GDK_KP_Add:
1397         case GDK_KP_Subtract:
1398                 return true;
1399         default:
1400                 return false;
1401         }
1402 }
1403
1404 AudioClock::Field
1405 AudioClock::index_to_field (int index) const
1406 {
1407         switch (_mode) {
1408         case Timecode:
1409                 if (index < 4) {
1410                         return Timecode_Hours;
1411                 } else if (index < 7) {
1412                         return Timecode_Minutes;
1413                 } else if (index < 10) {
1414                         return Timecode_Seconds;
1415                 } else {
1416                         return Timecode_Frames;
1417                 }
1418                 break;
1419         case BBT:
1420                 if (index < 5) {
1421                         return Bars;
1422                 } else if (index < 7) {
1423                         return Beats;
1424                 } else {
1425                         return Ticks;
1426                 }
1427                 break;
1428         case MinSec:
1429                 if (index < 3) {
1430                         return Timecode_Hours;
1431                 } else if (index < 6) {
1432                         return MS_Minutes;
1433                 } else if (index < 9) {
1434                         return MS_Seconds;
1435                 } else {
1436                         return MS_Milliseconds;
1437                 }
1438                 break;
1439         case Frames:
1440                 return AudioFrames;
1441                 break;
1442         }
1443
1444         return Field (0);
1445 }
1446
1447 bool
1448 AudioClock::on_button_press_event (GdkEventButton *ev)
1449 {
1450         switch (ev->button) {
1451         case 1:
1452                 if (editable && !_off) {
1453                         int index;
1454                         int trailing;
1455                         int y;
1456                         int x;
1457
1458                         /* the text has been centered vertically, so adjust
1459                          * x and y. 
1460                          */
1461
1462                         y = ev->y - ((upper_height - layout_height)/2);
1463                         x = ev->x - layout_x_offset;
1464                         
1465                         if (_layout->xy_to_index (x * PANGO_SCALE, y * PANGO_SCALE, index, trailing)) {
1466                                 drag_field = index_to_field (index);
1467                                 dragging = true;
1468                                 /* make absolutely sure that the pointer is grabbed */
1469                                 gdk_pointer_grab(ev->window,false ,
1470                                                  GdkEventMask( Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_PRESS_MASK |Gdk::BUTTON_RELEASE_MASK),
1471                                                  NULL,NULL,ev->time);
1472                                 drag_accum = 0;
1473                                 drag_start_y = ev->y;
1474                                 drag_y = ev->y;
1475                         }
1476                 }
1477                 break;
1478                 
1479         default:
1480                 return false;
1481                 break;
1482         }
1483
1484         return true;
1485 }
1486
1487 bool
1488 AudioClock::on_button_release_event (GdkEventButton *ev)
1489 {
1490         if (editable && !_off) {
1491                 if (dragging) {
1492                         gdk_pointer_ungrab (GDK_CURRENT_TIME);
1493                         dragging = false;
1494                         if (ev->y > drag_start_y+1 || ev->y < drag_start_y-1 || Keyboard::modifier_state_equals (ev->state, Keyboard::TertiaryModifier)){
1495                                 // we actually dragged so return without
1496                                 // setting editing focus, or we shift clicked
1497                                 return true;
1498                         } else {
1499                                 if (ev->button == 1) {
1500                                         
1501                                         if (_edit_by_click_field) {
1502
1503                                                 int index = 0;
1504                                                 int trailing;
1505                                                 int y = ev->y - ((upper_height - layout_height)/2);
1506                                                 int x = ev->x - layout_x_offset;
1507                                                 Field f;
1508
1509                                                 if (!_layout->xy_to_index (x * PANGO_SCALE, y * PANGO_SCALE, index, trailing)) {
1510                                                         return true;
1511                                                 }
1512                                                 
1513                                                 f = index_to_field (index);
1514                                                 
1515                                                 switch (f) {
1516                                                 case Timecode_Frames:
1517                                                 case MS_Milliseconds:
1518                                                 case Ticks:
1519                                                         f = Field (0);
1520                                                         break;
1521                                                 default:
1522                                                         break;
1523                                                 }
1524                                                 start_edit (f);
1525                                         } else {
1526                                                 start_edit ();
1527                                         }
1528                                 }
1529                         }
1530                 }
1531         }
1532
1533         if (Keyboard::is_context_menu_event (ev)) {
1534                 if (ops_menu == 0) {
1535                         build_ops_menu ();
1536                 }
1537                 ops_menu->popup (1, ev->time);
1538                 return true;
1539         }
1540
1541         return false;
1542 }
1543
1544 bool
1545 AudioClock::on_focus_out_event (GdkEventFocus* ev)
1546 {
1547         bool ret = CairoWidget::on_focus_out_event (ev);
1548
1549         if (editing) {
1550                 end_edit (false);
1551         }
1552
1553         return ret;
1554 }
1555
1556 bool
1557 AudioClock::on_scroll_event (GdkEventScroll *ev)
1558 {
1559         int index;
1560         int trailing;
1561
1562         if (editing || _session == 0 || !editable || _off) {
1563                 return false;
1564         }
1565
1566         int y;
1567         int x;
1568         
1569         /* the text has been centered vertically, so adjust
1570          * x and y. 
1571          */
1572
1573         y = ev->y - ((upper_height - layout_height)/2);
1574         x = ev->x - layout_x_offset;
1575
1576         if (!_layout->xy_to_index (x * PANGO_SCALE, y * PANGO_SCALE, index, trailing)) {
1577                 /* not in the main layout */
1578                 return false;
1579         }
1580         
1581         Field f = index_to_field (index);
1582         framepos_t frames = 0;
1583
1584         switch (ev->direction) {
1585
1586         case GDK_SCROLL_UP:
1587                 frames = get_frame_step (f);
1588                 if (frames != 0) {
1589                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
1590                                 frames *= 10;
1591                         }
1592                         set (current_time() + frames, true);
1593                         ValueChanged (); /* EMIT_SIGNAL */
1594                 }
1595                 break;
1596                 
1597         case GDK_SCROLL_DOWN:
1598                 frames = get_frame_step (f);
1599                 if (frames != 0) {
1600                         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier)) {
1601                                 frames *= 10;
1602                         }
1603                         
1604                         if ((double)current_time() - (double)frames < 0.0) {
1605                                 set (0, true);
1606                         } else {
1607                                 set (current_time() - frames, true);
1608                         }
1609                         
1610                         ValueChanged (); /* EMIT_SIGNAL */
1611                 }
1612                 break;
1613                 
1614         default:
1615                 return false;
1616                 break;
1617         }
1618         
1619         return true;
1620 }
1621
1622 bool
1623 AudioClock::on_motion_notify_event (GdkEventMotion *ev)
1624 {
1625         if (editing || _session == 0 || !dragging) {
1626                 return false;
1627         }
1628
1629         float pixel_frame_scale_factor = 0.2f;
1630
1631         if (Keyboard::modifier_state_equals (ev->state, Keyboard::PrimaryModifier))  {
1632                 pixel_frame_scale_factor = 0.1f;
1633         }
1634
1635
1636         if (Keyboard::modifier_state_contains (ev->state,
1637                                                Keyboard::PrimaryModifier|Keyboard::SecondaryModifier)) {
1638
1639                 pixel_frame_scale_factor = 0.025f;
1640         }
1641
1642         double y_delta = ev->y - drag_y;
1643
1644         drag_accum +=  y_delta*pixel_frame_scale_factor;
1645
1646         drag_y = ev->y;
1647
1648         if (trunc (drag_accum) != 0) {
1649
1650                 framepos_t frames;
1651                 framepos_t pos;
1652                 int dir;
1653                 dir = (drag_accum < 0 ? 1:-1);
1654                 pos = current_time();
1655                 frames = get_frame_step (drag_field, pos, dir);
1656
1657                 if (frames  != 0 &&  frames * drag_accum < current_time()) {
1658                         set ((framepos_t) floor (pos - drag_accum * frames), false); // minus because up is negative in GTK
1659                 } else {
1660                         set (0 , false);
1661                 }
1662
1663                 drag_accum= 0;
1664                 ValueChanged();  /* EMIT_SIGNAL */
1665         }
1666
1667         return true;
1668 }
1669
1670 framepos_t
1671 AudioClock::get_frame_step (Field field, framepos_t pos, int dir)
1672 {
1673         framecnt_t f = 0;
1674         Timecode::BBT_Time BBT;
1675         switch (field) {
1676         case Timecode_Hours:
1677                 f = (framecnt_t) floor (3600.0 * _session->frame_rate());
1678                 break;
1679         case Timecode_Minutes:
1680                 f = (framecnt_t) floor (60.0 * _session->frame_rate());
1681                 break;
1682         case Timecode_Seconds:
1683                 f = _session->frame_rate();
1684                 break;
1685         case Timecode_Frames:
1686                 f = (framecnt_t) floor (_session->frame_rate() / _session->timecode_frames_per_second());
1687                 break;
1688
1689         case AudioFrames:
1690                 f = 1;
1691                 break;
1692
1693         case MS_Hours:
1694                 f = (framecnt_t) floor (3600.0 * _session->frame_rate());
1695                 break;
1696         case MS_Minutes:
1697                 f = (framecnt_t) floor (60.0 * _session->frame_rate());
1698                 break;
1699         case MS_Seconds:
1700                 f = (framecnt_t) _session->frame_rate();
1701                 break;
1702         case MS_Milliseconds:
1703                 f = (framecnt_t) floor (_session->frame_rate() / 1000.0);
1704                 break;
1705
1706         case Bars:
1707                 BBT.bars = 1;
1708                 BBT.beats = 0;
1709                 BBT.ticks = 0;
1710                 f = _session->tempo_map().bbt_duration_at (pos,BBT,dir);
1711                 break;
1712         case Beats:
1713                 BBT.bars = 0;
1714                 BBT.beats = 1;
1715                 BBT.ticks = 0;
1716                 f = _session->tempo_map().bbt_duration_at(pos,BBT,dir);
1717                 break;
1718         case Ticks:
1719                 BBT.bars = 0;
1720                 BBT.beats = 0;
1721                 BBT.ticks = 1;
1722                 f = _session->tempo_map().bbt_duration_at(pos,BBT,dir);
1723                 break;
1724         default:
1725                 error << string_compose (_("programming error: %1"), "attempt to get frames from non-text field!") << endmsg;
1726                 f = 0;
1727                 break;
1728         }
1729
1730         return f;
1731 }
1732
1733 framepos_t
1734 AudioClock::current_time (framepos_t) const
1735 {
1736         return last_when;
1737 }
1738
1739 framepos_t
1740 AudioClock::current_duration (framepos_t pos) const
1741 {
1742         framepos_t ret = 0;
1743
1744         switch (_mode) {
1745         case Timecode:
1746                 ret = last_when;
1747                 break;
1748         case BBT:
1749                 ret = frame_duration_from_bbt_string (pos, _layout->get_text());
1750                 break;
1751
1752         case MinSec:
1753                 ret = last_when;
1754                 break;
1755
1756         case Frames:
1757                 ret = last_when;
1758                 break;
1759         }
1760
1761         return ret;
1762 }
1763
1764 bool
1765 AudioClock::bbt_validate_edit (const string& str)
1766 {
1767         AnyTime any;
1768
1769         if (sscanf (str.c_str(), BBT_SCANF_FORMAT, &any.bbt.bars, &any.bbt.beats, &any.bbt.ticks) != 3) {
1770                 return false;
1771         }
1772
1773         if (any.bbt.ticks > Timecode::BBT_Time::ticks_per_beat) {
1774                 return false;
1775         }
1776
1777         if (!is_duration && any.bbt.bars == 0) {
1778                 return false;
1779         }
1780
1781         if (!is_duration && any.bbt.beats == 0) {
1782                 return false;
1783         }
1784
1785         return true;
1786 }
1787
1788 bool
1789 AudioClock::timecode_validate_edit (const string&)
1790 {
1791         Timecode::Time TC;
1792
1793         if (sscanf (_layout->get_text().c_str(), "%" PRId32 ":%" PRId32 ":%" PRId32 ":%" PRId32, 
1794                     &TC.hours, &TC.minutes, &TC.seconds, &TC.frames) != 4) {
1795                 return false;
1796         }
1797
1798         if (TC.hours > 23U || TC.minutes > 59U || TC.seconds > 59U) {
1799                 return false;
1800         }
1801
1802         if (TC.frames > (uint32_t) rint (_session->timecode_frames_per_second()) - 1) {
1803                 return false;
1804         }
1805
1806         if (_session->timecode_drop_frames()) {
1807                 if (TC.minutes % 10 && TC.seconds == 0U && TC.frames < 2U) {
1808                         return false;
1809                 }
1810         }
1811
1812         return true;
1813 }
1814
1815 bool
1816 AudioClock::minsec_validate_edit (const string& str)
1817 {
1818         int hrs, mins, secs, millisecs;
1819
1820         if (sscanf (str.c_str(), "%d:%d:%d.%d", &hrs, &mins, &secs, &millisecs) != 4) {
1821                 return false;
1822         }
1823         
1824         if (hrs > 23 || mins > 59 || secs > 59 || millisecs > 999) {
1825                 return false;
1826         }
1827
1828         return true;
1829 }
1830
1831 framepos_t
1832 AudioClock::frames_from_timecode_string (const string& str) const
1833 {
1834         if (_session == 0) {
1835                 return 0;
1836         }
1837
1838         Timecode::Time TC;
1839         framepos_t sample;
1840
1841         if (sscanf (str.c_str(), "%d:%d:%d:%d", &TC.hours, &TC.minutes, &TC.seconds, &TC.frames) != 4) {
1842                 error << string_compose (_("programming error: %1 %2"), "badly formatted timecode clock string", str) << endmsg;
1843                 return 0;
1844         }
1845
1846         TC.rate = _session->timecode_frames_per_second();
1847         TC.drop= _session->timecode_drop_frames();
1848
1849         _session->timecode_to_sample (TC, sample, false /* use_offset */, false /* use_subframes */ );
1850         
1851         // timecode_tester ();
1852
1853         return sample;
1854 }
1855
1856 framepos_t
1857 AudioClock::frames_from_minsec_string (const string& str) const
1858 {
1859         if (_session == 0) {
1860                 return 0;
1861         }
1862
1863         int hrs, mins, secs, millisecs;
1864         framecnt_t sr = _session->frame_rate();
1865
1866         if (sscanf (str.c_str(), "%d:%d:%d.%d", &hrs, &mins, &secs, &millisecs) != 4) {
1867                 error << string_compose (_("programming error: %1 %2"), "badly formatted minsec clock string", str) << endmsg;
1868                 return 0;
1869         }
1870
1871         return (framepos_t) floor ((hrs * 60.0f * 60.0f * sr) + (mins * 60.0f * sr) + (secs * sr) + (millisecs * sr / 1000.0));
1872 }
1873
1874 framepos_t
1875 AudioClock::frames_from_bbt_string (framepos_t pos, const string& str) const
1876 {
1877         if (_session == 0) {
1878                 error << "AudioClock::current_time() called with BBT mode but without session!" << endmsg;
1879                 return 0;
1880         }
1881
1882         AnyTime any;
1883         any.type = AnyTime::BBT;
1884
1885         if (sscanf (str.c_str(), BBT_SCANF_FORMAT, &any.bbt.bars, &any.bbt.beats, &any.bbt.ticks) != 3) {
1886                 return 0;
1887         }
1888         
1889         if (is_duration) {
1890                 any.bbt.bars++;
1891                 any.bbt.beats++;
1892                 return _session->any_duration_to_frames (pos, any);
1893         } else {
1894                 return _session->convert_to_frames (any);
1895         }
1896 }
1897
1898
1899 framepos_t
1900 AudioClock::frame_duration_from_bbt_string (framepos_t pos, const string& str) const
1901 {
1902         if (_session == 0) {
1903                 error << "AudioClock::current_time() called with BBT mode but without session!" << endmsg;
1904                 return 0;
1905         }
1906
1907         Timecode::BBT_Time bbt;
1908
1909         if (sscanf (str.c_str(), BBT_SCANF_FORMAT, &bbt.bars, &bbt.beats, &bbt.ticks) != 3) {
1910                 return 0;
1911         }
1912
1913         return _session->tempo_map().bbt_duration_at(pos,bbt,1);
1914 }
1915
1916 framepos_t
1917 AudioClock::frames_from_audioframes_string (const string& str) const
1918 {
1919         framepos_t f;
1920         sscanf (str.c_str(), "%" PRId64, &f);
1921         return f;
1922 }
1923
1924 void
1925 AudioClock::build_ops_menu ()
1926 {
1927         using namespace Menu_Helpers;
1928         ops_menu = new Menu;
1929         MenuList& ops_items = ops_menu->items();
1930         ops_menu->set_name ("ArdourContextMenu");
1931
1932         if (!Profile->get_sae()) {
1933                 ops_items.push_back (MenuElem (_("Timecode"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), Timecode)));
1934         }
1935         ops_items.push_back (MenuElem (_("Bars:Beats"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), BBT)));
1936         ops_items.push_back (MenuElem (_("Minutes:Seconds"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), MinSec)));
1937         ops_items.push_back (MenuElem (_("Samples"), sigc::bind (sigc::mem_fun(*this, &AudioClock::set_mode), Frames)));
1938
1939         if (editable && !_off && !is_duration && !_follows_playhead) {
1940                 ops_items.push_back (SeparatorElem());
1941                 ops_items.push_back (MenuElem (_("Set From Playhead"), sigc::mem_fun(*this, &AudioClock::set_from_playhead)));
1942                 ops_items.push_back (MenuElem (_("Locate to This Time"), sigc::mem_fun(*this, &AudioClock::locate)));
1943         }
1944 }
1945
1946 void
1947 AudioClock::set_from_playhead ()
1948 {
1949         if (!_session) {
1950                 return;
1951         }
1952
1953         set (_session->transport_frame());
1954         ValueChanged ();
1955 }
1956
1957 void
1958 AudioClock::locate ()
1959 {
1960         if (!_session || is_duration) {
1961                 return;
1962         }
1963
1964         _session->request_locate (current_time(), _session->transport_rolling ());
1965 }
1966
1967 void
1968 AudioClock::set_mode (Mode m)
1969 {
1970         if (_mode == m) {
1971                 return;
1972         }
1973
1974         _mode = m;
1975
1976         insert_map.clear();
1977
1978         _layout->set_text ("");
1979
1980         if (_left_layout) {
1981                 _left_layout->set_text ("");
1982                 _right_layout->set_text ("");
1983         }
1984
1985         switch (_mode) {
1986         case Timecode:
1987                 mode_based_info_ratio = 0.5;
1988                 insert_map.push_back (11);
1989                 insert_map.push_back (10);
1990                 insert_map.push_back (8);
1991                 insert_map.push_back (7);
1992                 insert_map.push_back (5);
1993                 insert_map.push_back (4);
1994                 insert_map.push_back (2);
1995                 insert_map.push_back (1);
1996                 break;
1997                 
1998         case BBT:
1999                 mode_based_info_ratio = 0.5;
2000                 insert_map.push_back (11);
2001                 insert_map.push_back (10);
2002                 insert_map.push_back (9);
2003                 insert_map.push_back (8);
2004                 insert_map.push_back (6);
2005                 insert_map.push_back (5);       
2006                 insert_map.push_back (3);       
2007                 insert_map.push_back (2);       
2008                 insert_map.push_back (1);       
2009                 break;
2010                 
2011         case MinSec:
2012                 mode_based_info_ratio = 1.0;
2013                 insert_map.push_back (12);
2014                 insert_map.push_back (11);
2015                 insert_map.push_back (10);
2016                 insert_map.push_back (8);
2017                 insert_map.push_back (7);
2018                 insert_map.push_back (5);
2019                 insert_map.push_back (4);
2020                 insert_map.push_back (2);       
2021                 insert_map.push_back (1);       
2022                 break;
2023                 
2024         case Frames:
2025                 mode_based_info_ratio = 0.5;
2026                 break;
2027         }
2028
2029         set (last_when, true);
2030
2031         if (!is_transient) {
2032                 ModeChanged (); /* EMIT SIGNAL (the static one)*/
2033         }
2034
2035         if (!_fixed_width) {
2036                 /* display is different, allow us to resize */
2037                 first_width = 0;
2038                 first_height = 0;
2039                 queue_resize ();
2040         }
2041
2042         mode_changed (); /* EMIT SIGNAL (the member one) */
2043 }
2044
2045 void
2046 AudioClock::set_bbt_reference (framepos_t pos)
2047 {
2048         bbt_reference_time = pos;
2049 }
2050
2051 void
2052 AudioClock::on_style_changed (const Glib::RefPtr<Gtk::Style>& old_style)
2053 {
2054         CairoWidget::on_style_changed (old_style);
2055         set_font ();
2056         set_colors ();
2057 }
2058
2059 void
2060 AudioClock::set_editable (bool yn)
2061 {
2062         editable = yn;
2063 }
2064
2065 void
2066 AudioClock::set_is_duration (bool yn)
2067 {
2068         if (yn == is_duration) {
2069                 return;
2070         }
2071
2072         is_duration = yn;
2073         set (last_when, true);
2074 }
2075
2076 void
2077 AudioClock::set_off (bool yn) 
2078 {
2079         if (_off == yn) {
2080                 return;
2081         }
2082
2083         _off = yn;
2084
2085         /* force a redraw. last_when will be preserved, but the clock text will
2086          * change 
2087          */
2088         
2089         set (last_when, true);
2090 }
2091
2092 void
2093 AudioClock::focus ()
2094 {
2095         start_edit (Field (0));
2096 }
2097
2098 void
2099 AudioClock::set_corner_radius (double r)
2100 {
2101         corner_radius = r;
2102         queue_draw ();
2103 }
2104
2105 void
2106 AudioClock::set_fixed_width (bool yn)
2107 {
2108         _fixed_width = yn;
2109 }
2110
2111 void
2112 AudioClock::dpi_reset ()
2113 {
2114         /* force recomputation of size even if we are fixed width 
2115          */
2116         first_width = 0;
2117         first_height = 0;
2118         queue_resize ();
2119 }