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