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