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