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