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