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