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