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