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