merge with master.
[ardour.git] / libs / ardour / location.cc
1 /*
2     Copyright (C) 2000 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 <algorithm>
21 #include <set>
22 #include <cstdio> /* for sprintf */
23 #include <unistd.h>
24 #include <cerrno>
25 #include <ctime>
26 #include <list>
27
28 #include "pbd/stl_delete.h"
29 #include "pbd/xml++.h"
30 #include "pbd/enumwriter.h"
31
32 #include "ardour/location.h"
33 #include "ardour/midi_scene_change.h"
34 #include "ardour/session.h"
35 #include "ardour/audiofilesource.h"
36 #include "ardour/tempo.h"
37
38 #include "i18n.h"
39
40 #define SUFFIX_MAX 32
41
42 using namespace std;
43 using namespace ARDOUR;
44 using namespace PBD;
45
46 PBD::Signal0<void> Location::scene_changed;
47
48 Location::Location (Session& s)
49         : SessionHandleRef (s)
50         , _start (0)
51         , _end (0)
52         , _flags (Flags (0))
53         , _locked (false)
54         , _position_lock_style (AudioTime)
55 {
56         assert (_start >= 0);
57         assert (_end >= 0);
58 }
59
60 /** Construct a new Location, giving it the position lock style determined by glue-new-markers-to-bars-and-beats */
61 Location::Location (Session& s, framepos_t sample_start, framepos_t sample_end, const std::string &name, Flags bits)
62         : SessionHandleRef (s)
63         , _name (name)
64         , _start (sample_start)
65         , _end (sample_end)
66         , _flags (bits)
67         , _locked (false)
68         , _position_lock_style (s.config.get_glue_new_markers_to_bars_and_beats() ? MusicTime : AudioTime)
69 {
70         recompute_bbt_from_frames ();
71
72         assert (_start >= 0);
73         assert (_end >= 0);
74 }
75
76 Location::Location (const Location& other)
77         : SessionHandleRef (other._session)
78         , StatefulDestructible()
79         , _name (other._name)
80         , _start (other._start)
81         , _bbt_start (other._bbt_start)
82         , _end (other._end)
83         , _bbt_end (other._bbt_end)
84         , _flags (other._flags)
85         , _position_lock_style (other._position_lock_style)
86 {
87         /* copy is not locked even if original was */
88
89         _locked = false;
90
91         assert (_start >= 0);
92         assert (_end >= 0);
93
94         /* scene change is NOT COPIED */
95 }
96
97 Location::Location (Session& s, const XMLNode& node)
98         : SessionHandleRef (s)
99         , _position_lock_style (AudioTime)
100 {
101         /* Note: _position_lock_style is initialised above in case set_state doesn't set it
102            (for 2.X session file compatibility).
103         */
104
105         if (set_state (node, Stateful::loading_state_version)) {
106                 throw failed_constructor ();
107         }
108
109         assert (_start >= 0);
110         assert (_end >= 0);
111 }
112
113 bool
114 Location::operator== (const Location& other)
115 {
116         if (_name != other._name ||
117             _start != other._start ||
118             _end != other._end ||
119             _bbt_start != other._bbt_start ||
120             _bbt_end != other._bbt_end ||
121             _flags != other._flags ||
122             _position_lock_style != other._position_lock_style) {
123                 return false;
124         }
125         return true;
126 }
127
128 Location*
129 Location::operator= (const Location& other)
130 {
131         if (this == &other) {
132                 return this;
133         }
134
135         _name = other._name;
136         _start = other._start;
137         _bbt_start = other._bbt_start;
138         _end = other._end;
139         _bbt_end = other._bbt_end;
140         _flags = other._flags;
141         _position_lock_style = other._position_lock_style;
142         
143         /* XXX need to copy scene change */
144
145         /* copy is not locked even if original was */
146
147         _locked = false;
148
149         /* "changed" not emitted on purpose */
150
151         assert (_start >= 0);
152         assert (_end >= 0);
153
154         return this;
155 }
156
157 /** Set start position.
158  *  @param s New start.
159  *  @param force true to force setting, even if the given new start is after the current end.
160  *  @param allow_bbt_recompute True to recompute BBT start time from the new given start time.
161  */
162 int
163 Location::set_start (framepos_t s, bool force, bool allow_bbt_recompute)
164 {
165         if (s < 0) {
166                 return -1;
167         }
168
169         if (_locked) {
170                 return -1;
171         }
172
173         if (!force) {
174                 if (((is_auto_punch() || is_auto_loop()) && s >= _end) || (!is_mark() && s > _end)) {
175                         return -1;
176                 }
177         }
178
179         if (is_mark()) {
180                 if (_start != s) {
181                         _start = s;
182                         _end = s;
183                         if (allow_bbt_recompute) {
184                                 recompute_bbt_from_frames ();
185                         }
186
187                         start_changed (this); /* EMIT SIGNAL */
188                         end_changed (this); /* EMIT SIGNAL */
189                 }
190
191                 /* moving the start (position) of a marker with a scene change
192                    requires an update in the Scene Changer.
193                 */
194
195                 if (_scene_change) {
196                         scene_changed (); /* EMIT SIGNAL */
197                 }
198
199                 assert (_start >= 0);
200                 assert (_end >= 0);
201
202                 return 0;
203         }
204
205         if (s != _start) {
206
207                 framepos_t const old = _start;
208
209                 _start = s;
210                 if (allow_bbt_recompute) {
211                         recompute_bbt_from_frames ();
212                 }
213                 start_changed (this); /* EMIT SIGNAL */
214                                 
215                 if (is_session_range ()) {
216                         Session::StartTimeChanged (old); /* EMIT SIGNAL */
217                         AudioFileSource::set_header_position_offset (s);
218                 }
219         }
220
221         assert (_start >= 0);
222
223         return 0;
224 }
225
226 /** Set end position.
227  *  @param s New end.
228  *  @param force true to force setting, even if the given new start is after the current end.
229  *  @param allow_bbt_recompute True to recompute BBT end time from the new given end time.
230  */
231 int
232 Location::set_end (framepos_t e, bool force, bool allow_bbt_recompute)
233 {
234         if (e < 0) {
235                 return -1;
236         }
237
238         if (_locked) {
239                 return -1;
240         }
241
242         if (!force) {
243                 if (((is_auto_punch() || is_auto_loop()) && e <= _start) || e < _start) {
244                         return -1;
245                 }
246         }
247
248         if (is_mark()) {
249                 if (_start != e) {
250                         _start = e;
251                         _end = e;
252                         if (allow_bbt_recompute) {
253                                 recompute_bbt_from_frames ();
254                         }
255                         start_changed (this); /* EMIT SIGNAL */
256                         end_changed (this); /* EMIT SIGNAL */
257                 }
258
259                 assert (_start >= 0);
260                 assert (_end >= 0);
261
262                 return 0;
263         }
264
265         if (e != _end) {
266
267                 framepos_t const old = _end;
268
269                 _end = e;
270                 if (allow_bbt_recompute) {
271                         recompute_bbt_from_frames ();
272                 }
273                 end_changed(this); /* EMIT SIGNAL */
274
275                 if (is_session_range()) {
276                         Session::EndTimeChanged (old); /* EMIT SIGNAL */
277                 }
278         }
279
280         assert (_end >= 0);
281
282         return 0;
283 }
284
285 int
286 Location::set (framepos_t start, framepos_t end, bool allow_bbt_recompute)
287 {
288         if (start < 0 || end < 0) {
289                 return -1;
290         }
291
292         /* check validity */
293         if (((is_auto_punch() || is_auto_loop()) && start >= end) || (!is_mark() && start > end)) {
294                 return -1;
295         }
296
297         /* now we know these values are ok, so force-set them */
298         int const s = set_start (start, true, allow_bbt_recompute);
299         int const e = set_end (end, true, allow_bbt_recompute);
300
301         return (s == 0 && e == 0) ? 0 : -1;
302 }
303
304 int
305 Location::move_to (framepos_t pos)
306 {
307         if (pos < 0) {
308                 return -1;
309         }
310
311         if (_locked) {
312                 return -1;
313         }
314
315         if (_start != pos) {
316                 _start = pos;
317                 _end = _start + length();
318                 recompute_bbt_from_frames ();
319
320                 changed (this); /* EMIT SIGNAL */
321         }
322
323         assert (_start >= 0);
324         assert (_end >= 0);
325
326         return 0;
327 }
328
329 void
330 Location::set_hidden (bool yn, void *src)
331 {
332         if (set_flag_internal (yn, IsHidden)) {
333                  FlagsChanged (this, src); /* EMIT SIGNAL */
334         }
335 }
336
337 void
338 Location::set_cd (bool yn, void *src)
339 {
340         // XXX this really needs to be session start
341         // but its not available here - leave to GUI
342
343         if (_start == 0) {
344                 error << _("You cannot put a CD marker at this position") << endmsg;
345                 return;
346         }
347
348         if (set_flag_internal (yn, IsCDMarker)) {
349                  FlagsChanged (this, src); /* EMIT SIGNAL */
350         }
351 }
352
353 void
354 Location::set_is_range_marker (bool yn, void *src)
355 {
356        if (set_flag_internal (yn, IsRangeMarker)) {
357                 FlagsChanged (this, src); /* EMIT SIGNAL */
358        }
359 }
360
361 void
362 Location::set_auto_punch (bool yn, void *src)
363 {
364         if (is_mark() || _start == _end) {
365                 return;
366         }
367
368         if (set_flag_internal (yn, IsAutoPunch)) {
369                  FlagsChanged (this, src); /* EMIT SIGNAL */
370         }
371 }
372
373 void
374 Location::set_auto_loop (bool yn, void *src)
375 {
376         if (is_mark() || _start == _end) {
377                 return;
378         }
379
380         if (set_flag_internal (yn, IsAutoLoop)) {
381                  FlagsChanged (this, src); /* EMIT SIGNAL */
382         }
383 }
384
385 bool
386 Location::set_flag_internal (bool yn, Flags flag)
387 {
388         if (yn) {
389                 if (!(_flags & flag)) {
390                         _flags = Flags (_flags | flag);
391                         return true;
392                 }
393         } else {
394                 if (_flags & flag) {
395                         _flags = Flags (_flags & ~flag);
396                         return true;
397                 }
398         }
399         return false;
400 }
401
402 void
403 Location::set_mark (bool yn)
404 {
405         /* This function is private, and so does not emit signals */
406
407         if (_start != _end) {
408                 return;
409         }
410
411         set_flag_internal (yn, IsMark);
412 }
413
414
415 XMLNode&
416 Location::cd_info_node(const string & name, const string & value)
417 {
418         XMLNode* root = new XMLNode("CD-Info");
419
420         root->add_property("name", name);
421         root->add_property("value", value);
422
423         return *root;
424 }
425
426
427 XMLNode&
428 Location::get_state ()
429 {
430         XMLNode *node = new XMLNode ("Location");
431         char buf[64];
432
433         typedef map<string, string>::const_iterator CI;
434
435         for(CI m = cd_info.begin(); m != cd_info.end(); ++m){
436                 node->add_child_nocopy(cd_info_node(m->first, m->second));
437         }
438
439         id().print (buf, sizeof (buf));
440         node->add_property("id", buf);
441         node->add_property ("name", name());
442         snprintf (buf, sizeof (buf), "%" PRId64, start());
443         node->add_property ("start", buf);
444         snprintf (buf, sizeof (buf), "%" PRId64, end());
445         node->add_property ("end", buf);
446         node->add_property ("flags", enum_2_string (_flags));
447         node->add_property ("locked", (_locked ? "yes" : "no"));
448         node->add_property ("position-lock-style", enum_2_string (_position_lock_style));
449
450         if (_scene_change) {
451                 node->add_child_nocopy (_scene_change->get_state());
452         }
453
454         return *node;
455 }
456
457 int
458 Location::set_state (const XMLNode& node, int version)
459 {
460         const XMLProperty *prop;
461
462         XMLNodeList cd_list = node.children();
463         XMLNodeConstIterator cd_iter;
464         XMLNode *cd_node;
465
466         string cd_name;
467         string cd_value;
468
469         if (node.name() != "Location") {
470                 error << _("incorrect XML node passed to Location::set_state") << endmsg;
471                 return -1;
472         }
473
474         if (!set_id (node)) {
475                 warning << _("XML node for Location has no ID information") << endmsg;
476         }
477
478         if ((prop = node.property ("name")) == 0) {
479                 error << _("XML node for Location has no name information") << endmsg;
480                 return -1;
481         }
482
483         set_name (prop->value());
484
485         if ((prop = node.property ("start")) == 0) {
486                 error << _("XML node for Location has no start information") << endmsg;
487                 return -1;
488         }
489
490                 /* can't use set_start() here, because _end
491                    may make the value of _start illegal.
492                 */
493
494         sscanf (prop->value().c_str(), "%" PRId64, &_start);
495
496         if ((prop = node.property ("end")) == 0) {
497                   error << _("XML node for Location has no end information") << endmsg;
498                   return -1;
499         }
500
501         sscanf (prop->value().c_str(), "%" PRId64, &_end);
502
503         if ((prop = node.property ("flags")) == 0) {
504                   error << _("XML node for Location has no flags information") << endmsg;
505                   return -1;
506         }
507
508         _flags = Flags (string_2_enum (prop->value(), _flags));
509
510         if ((prop = node.property ("locked")) != 0) {
511                 _locked = string_is_affirmative (prop->value());
512         } else {
513                 _locked = false;
514         }
515
516         for (cd_iter = cd_list.begin(); cd_iter != cd_list.end(); ++cd_iter) {
517
518                   cd_node = *cd_iter;
519
520                   if (cd_node->name() != "CD-Info") {
521                           continue;
522                   }
523
524                   if ((prop = cd_node->property ("name")) != 0) {
525                           cd_name = prop->value();
526                   } else {
527                           throw failed_constructor ();
528                   }
529
530                   if ((prop = cd_node->property ("value")) != 0) {
531                           cd_value = prop->value();
532                   } else {
533                           throw failed_constructor ();
534                   }
535
536
537                   cd_info[cd_name] = cd_value;
538         }
539
540         if ((prop = node.property ("position-lock-style")) != 0) {
541                 _position_lock_style = PositionLockStyle (string_2_enum (prop->value(), _position_lock_style));
542         }
543
544         XMLNode* scene_child = find_named_node (node, SceneChange::xml_node_name);
545         
546         if (scene_child) {
547                 _scene_change = SceneChange::factory (*scene_child, version);
548         }
549
550         recompute_bbt_from_frames ();
551
552         changed (this); /* EMIT SIGNAL */
553
554         assert (_start >= 0);
555         assert (_end >= 0);
556
557         return 0;
558 }
559
560 void
561 Location::set_position_lock_style (PositionLockStyle ps)
562 {
563         if (_position_lock_style == ps) {
564                 return;
565         }
566
567         _position_lock_style = ps;
568
569         recompute_bbt_from_frames ();
570
571         PositionLockStyleChanged (this); /* EMIT SIGNAL */
572 }
573
574 void
575 Location::recompute_bbt_from_frames ()
576 {
577         if (_position_lock_style != MusicTime) {
578                 return;
579         }
580
581         _session.bbt_time (_start, _bbt_start);
582         _session.bbt_time (_end, _bbt_end);
583 }
584
585 void
586 Location::recompute_frames_from_bbt ()
587 {
588         if (_position_lock_style != MusicTime) {
589                 return;
590         }
591
592         TempoMap& map (_session.tempo_map());
593         set (map.frame_time (_bbt_start), map.frame_time (_bbt_end), false);
594 }
595
596 void
597 Location::lock ()
598 {
599         _locked = true;
600         LockChanged (this);
601 }
602
603 void
604 Location::unlock ()
605 {
606         _locked = false;
607         LockChanged (this);
608 }
609
610 void
611 Location::set_scene_change (boost::shared_ptr<SceneChange>  sc)
612 {
613         _scene_change = sc;
614
615         scene_changed (); /* EMIT SIGNAL */
616 }
617
618 /*---------------------------------------------------------------------- */
619
620 Locations::Locations (Session& s)
621         : SessionHandleRef (s)
622 {
623         current_location = 0;
624 }
625
626 Locations::~Locations ()
627 {
628         for (LocationList::iterator i = locations.begin(); i != locations.end(); ) {
629                 LocationList::iterator tmp = i;
630                 ++tmp;
631                 delete *i;
632                 i = tmp;
633         }
634 }
635
636 int
637 Locations::set_current (Location *loc, bool want_lock)
638 {
639         int ret;
640
641         if (want_lock) {
642                 Glib::Threads::Mutex::Lock lm (lock);
643                 ret = set_current_unlocked (loc);
644         } else {
645                 ret = set_current_unlocked (loc);
646         }
647
648         if (ret == 0) {
649                  current_changed (current_location); /* EMIT SIGNAL */
650         }
651         return ret;
652 }
653
654 int
655 Locations::next_available_name(string& result,string base)
656 {
657         LocationList::iterator i;
658         Location* location;
659         string temp;
660         string::size_type l;
661         int suffix;
662         char buf[32];
663         bool available[SUFFIX_MAX+1];
664
665         result = base;
666         for (int k=1; k<SUFFIX_MAX; k++) {
667                 available[k] = true;
668         }
669         l = base.length();
670         for (i = locations.begin(); i != locations.end(); ++i) {
671                 location =* i;
672                 temp = location->name();
673                 if (l && !temp.find(base,0)) {
674                         suffix = atoi(temp.substr(l,3).c_str());
675                         if (suffix) available[suffix] = false;
676                 }
677         }
678         for (int k=1; k<=SUFFIX_MAX; k++) {
679                 if (available[k]) {
680                         snprintf (buf, 31, "%d", k);
681                         result += buf;
682                         return 1;
683                 }
684         }
685         return 0;
686 }
687
688 int
689 Locations::set_current_unlocked (Location *loc)
690 {
691         if (find (locations.begin(), locations.end(), loc) == locations.end()) {
692                 error << _("Locations: attempt to use unknown location as selected location") << endmsg;
693                 return -1;
694         }
695
696         current_location = loc;
697         return 0;
698 }
699
700 void
701 Locations::clear ()
702 {
703         {
704                 Glib::Threads::Mutex::Lock lm (lock);
705
706                 for (LocationList::iterator i = locations.begin(); i != locations.end(); ) {
707
708                         LocationList::iterator tmp = i;
709                         ++tmp;
710
711                         if (!(*i)->is_session_range()) {
712                                 delete *i;
713                                 locations.erase (i);
714                         }
715
716                         i = tmp;
717                 }
718
719                 current_location = 0;
720         }
721
722         changed (OTHER); /* EMIT SIGNAL */
723         current_changed (0); /* EMIT SIGNAL */
724 }
725
726 void
727 Locations::clear_markers ()
728 {
729         {
730                 Glib::Threads::Mutex::Lock lm (lock);
731                 LocationList::iterator tmp;
732
733                 for (LocationList::iterator i = locations.begin(); i != locations.end(); ) {
734                         tmp = i;
735                         ++tmp;
736
737                         if ((*i)->is_mark() && !(*i)->is_session_range()) {
738                                 delete *i;
739                                 locations.erase (i);
740                         }
741
742                         i = tmp;
743                 }
744         }
745
746         changed (OTHER); /* EMIT SIGNAL */
747 }
748
749 void
750 Locations::clear_ranges ()
751 {
752         {
753                 Glib::Threads::Mutex::Lock lm (lock);
754                 LocationList::iterator tmp;
755
756                 for (LocationList::iterator i = locations.begin(); i != locations.end(); ) {
757
758                         tmp = i;
759                         ++tmp;
760
761                         if (!(*i)->is_mark()) {
762                                 delete *i;
763                                 locations.erase (i);
764
765                         }
766
767                         i = tmp;
768                 }
769
770                 current_location = 0;
771         }
772
773         changed (OTHER); /* EMIT SIGNAL */
774         current_changed (0); /* EMIT SIGNAL */
775 }
776
777 void
778 Locations::add (Location *loc, bool make_current)
779 {
780         assert (loc);
781
782         {
783                 Glib::Threads::Mutex::Lock lm (lock);
784                 locations.push_back (loc);
785
786                 if (make_current) {
787                         current_location = loc;
788                 }
789         }
790
791         added (loc); /* EMIT SIGNAL */
792
793         if (make_current) {
794                  current_changed (current_location); /* EMIT SIGNAL */
795         }
796
797         if (loc->is_session_range()) {
798                 Session::StartTimeChanged (0);
799                 Session::EndTimeChanged (1);
800         }
801 }
802
803 void
804 Locations::remove (Location *loc)
805 {
806         bool was_removed = false;
807         bool was_current = false;
808         LocationList::iterator i;
809
810         if (loc->is_session_range()) {
811                 return;
812         }
813
814         {
815                 Glib::Threads::Mutex::Lock lm (lock);
816
817                 for (i = locations.begin(); i != locations.end(); ++i) {
818                         if ((*i) == loc) {
819                                 delete *i;
820                                 locations.erase (i);
821                                 was_removed = true;
822                                 if (current_location == loc) {
823                                         current_location = 0;
824                                         was_current = true;
825                                 }
826                                 break;
827                         }
828                 }
829         }
830
831         if (was_removed) {
832
833                 removed (loc); /* EMIT SIGNAL */
834
835                 if (was_current) {
836                          current_changed (0); /* EMIT SIGNAL */
837                 }
838
839                 changed (REMOVAL); /* EMIT_SIGNAL */
840         }
841 }
842
843 void
844 Locations::location_changed (Location* /*loc*/)
845 {
846         changed (OTHER); /* EMIT SIGNAL */
847 }
848
849 XMLNode&
850 Locations::get_state ()
851 {
852         XMLNode *node = new XMLNode ("Locations");
853         LocationList::iterator iter;
854         Glib::Threads::Mutex::Lock lm (lock);
855
856         for (iter = locations.begin(); iter != locations.end(); ++iter) {
857                 node->add_child_nocopy ((*iter)->get_state ());
858         }
859
860         return *node;
861 }
862
863 int
864 Locations::set_state (const XMLNode& node, int version)
865 {
866         if (node.name() != "Locations") {
867                 error << _("incorrect XML mode passed to Locations::set_state") << endmsg;
868                 return -1;
869         }
870
871         XMLNodeList nlist = node.children();
872
873         /* build up a new locations list in here */
874         LocationList new_locations;
875
876         current_location = 0;
877
878         Location* session_range_location = 0;
879         if (version < 3000) {
880                 session_range_location = new Location (_session, 0, 0, _("session"), Location::IsSessionRange);
881                 new_locations.push_back (session_range_location);
882         }
883
884         {
885                 Glib::Threads::Mutex::Lock lm (lock);
886
887                 XMLNodeConstIterator niter;
888                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
889
890                         try {
891
892                                 XMLProperty const * prop_id = (*niter)->property ("id");
893                                 assert (prop_id);
894                                 PBD::ID id (prop_id->value ());
895
896                                 LocationList::const_iterator i = locations.begin();
897                                 while (i != locations.end () && (*i)->id() != id) {
898                                         ++i;
899                                 }
900
901                                 Location* loc;
902                                 if (i != locations.end()) {
903                                         /* we can re-use an old Location object */
904                                         loc = *i;
905                                         loc->set_state (**niter, version);
906                                 } else {
907                                         loc = new Location (_session, **niter);
908                                 }
909
910                                 bool add = true;
911
912                                 if (version < 3000) {
913                                         /* look for old-style IsStart / IsEnd properties in this location;
914                                            if they are present, update the session_range_location accordingly
915                                         */
916                                         XMLProperty const * prop = (*niter)->property ("flags");
917                                         if (prop) {
918                                                 string v = prop->value ();
919                                                 while (1) {
920                                                         string::size_type const c = v.find_first_of (',');
921                                                         string const s = v.substr (0, c);
922                                                         if (s == X_("IsStart")) {
923                                                                 session_range_location->set_start (loc->start(), true);
924                                                                 add = false;
925                                                         } else if (s == X_("IsEnd")) {
926                                                                 session_range_location->set_end (loc->start(), true);
927                                                                 add = false;
928                                                         }
929
930                                                         if (c == string::npos) {
931                                                                 break;
932                                                         }
933
934                                                         v = v.substr (c + 1);
935                                                 }
936                                         }
937                                 }
938
939                                 if (add) {
940                                         new_locations.push_back (loc);
941                                 }
942                         }
943
944                         catch (failed_constructor& err) {
945                                 error << _("could not load location from session file - ignored") << endmsg;
946                         }
947                 }
948
949                 locations = new_locations;
950
951                 if (locations.size()) {
952                         current_location = locations.front();
953                 } else {
954                         current_location = 0;
955                 }
956         }
957
958         changed (OTHER); /* EMIT SIGNAL */
959
960         return 0;
961 }
962
963
964 typedef std::pair<framepos_t,Location*> LocationPair;
965
966 struct LocationStartEarlierComparison
967 {
968     bool operator() (LocationPair a, LocationPair b) {
969             return a.first < b.first;
970     }
971 };
972
973 struct LocationStartLaterComparison
974 {
975     bool operator() (LocationPair a, LocationPair b) {
976             return a.first > b.first;
977     }
978 };
979
980 framepos_t
981 Locations::first_mark_before (framepos_t frame, bool include_special_ranges)
982 {
983         Glib::Threads::Mutex::Lock lm (lock);
984         vector<LocationPair> locs;
985         
986         for (LocationList::iterator i = locations.begin(); i != locations.end(); ++i) {
987                 locs.push_back (make_pair ((*i)->start(), (*i)));
988                 if (!(*i)->is_mark()) {
989                         locs.push_back (make_pair ((*i)->end(), (*i)));
990                 }
991         }
992
993         LocationStartLaterComparison cmp;
994         sort (locs.begin(), locs.end(), cmp);
995
996         /* locs is sorted in ascending order */
997
998         for (vector<LocationPair>::iterator i = locs.begin(); i != locs.end(); ++i) {
999                 if ((*i).second->is_hidden()) {
1000                         continue;
1001                 }
1002                 if (!include_special_ranges && ((*i).second->is_auto_loop() || (*i).second->is_auto_punch())) {
1003                         continue;
1004                 }
1005                 if ((*i).first < frame) {
1006                         return (*i).first;
1007                 }
1008         }
1009
1010         return -1;
1011 }
1012
1013 Location*
1014 Locations::mark_at (framepos_t pos, framecnt_t slop) const
1015 {
1016         Glib::Threads::Mutex::Lock lm (lock);
1017         Location* closest = 0;
1018         frameoffset_t mindelta = max_framepos;
1019         frameoffset_t delta;
1020
1021         /* locations are not necessarily stored in linear time order so we have
1022          * to iterate across all of them to find the one closest to a give point.
1023          */
1024
1025         for (LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1026
1027                 if ((*i)->is_mark()) {
1028                         if (pos > (*i)->start()) { 
1029                                 delta = pos - (*i)->start();
1030                         } else {
1031                                 delta = (*i)->start() - pos;
1032                         }
1033                         
1034                         if (slop == 0 && delta == 0) {
1035                                 /* special case: no slop, and direct hit for position */
1036                                 return *i;
1037                         }
1038
1039                         if (delta <= slop) {
1040                                 if (delta < mindelta) {
1041                                         closest = *i;
1042                                         mindelta = delta;
1043                                 }
1044                         }
1045                 }
1046         }
1047
1048         return closest;
1049 }
1050
1051 framepos_t
1052 Locations::first_mark_after (framepos_t frame, bool include_special_ranges)
1053 {
1054         Glib::Threads::Mutex::Lock lm (lock);
1055         vector<LocationPair> locs;
1056
1057         for (LocationList::iterator i = locations.begin(); i != locations.end(); ++i) {
1058                 locs.push_back (make_pair ((*i)->start(), (*i)));
1059                 if (!(*i)->is_mark()) {
1060                         locs.push_back (make_pair ((*i)->end(), (*i)));
1061                 }
1062         }
1063
1064         LocationStartEarlierComparison cmp;
1065         sort (locs.begin(), locs.end(), cmp);
1066         
1067         /* locs is sorted in reverse order */
1068
1069         for (vector<LocationPair>::iterator i = locs.begin(); i != locs.end(); ++i) {
1070                 if ((*i).second->is_hidden()) {
1071                         continue;
1072                 }
1073                 if (!include_special_ranges && ((*i).second->is_auto_loop() || (*i).second->is_auto_punch())) {
1074                         continue;
1075                 }
1076                 if ((*i).first > frame) {
1077                         return (*i).first;
1078                 }
1079         }
1080
1081         return -1;
1082 }
1083
1084 /** Look for the `marks' (either locations which are marks, or start/end points of range markers) either
1085  *  side of a frame.  Note that if frame is exactly on a `mark', that mark will not be considered for returning
1086  *  as before/after.
1087  *  @param frame Frame to look for.
1088  *  @param before Filled in with the position of the last `mark' before `frame' (or max_framepos if none exists)
1089  *  @param after Filled in with the position of the next `mark' after `frame' (or max_framepos if none exists)
1090  */
1091 void
1092 Locations::marks_either_side (framepos_t const frame, framepos_t& before, framepos_t& after) const
1093 {
1094         before = after = max_framepos;
1095
1096         LocationList locs;
1097
1098         {
1099                 Glib::Threads::Mutex::Lock lm (lock);
1100                 locs = locations;
1101         }
1102
1103         /* Get a list of positions; don't store any that are exactly on our requested position */
1104
1105         std::list<framepos_t> positions;
1106
1107         for (LocationList::const_iterator i = locs.begin(); i != locs.end(); ++i) {
1108                 if (((*i)->is_auto_loop() || (*i)->is_auto_punch())) {
1109                         continue;
1110                 }
1111
1112                 if (!(*i)->is_hidden()) {
1113                         if ((*i)->is_mark ()) {
1114                                 if ((*i)->start() != frame) {
1115                                         positions.push_back ((*i)->start ());
1116                                 }
1117                         } else {
1118                                 if ((*i)->start() != frame) {
1119                                         positions.push_back ((*i)->start ());
1120                                 }
1121                                 if ((*i)->end() != frame) {
1122                                         positions.push_back ((*i)->end ());
1123                                 }
1124                         }
1125                 }
1126         }
1127
1128         if (positions.empty ()) {
1129                 return;
1130         }
1131
1132         positions.sort ();
1133
1134         std::list<framepos_t>::iterator i = positions.begin ();
1135         while (i != positions.end () && *i < frame) {
1136                 ++i;
1137         }
1138
1139         if (i == positions.end ()) {
1140                 /* run out of marks */
1141                 before = positions.back ();
1142                 return;
1143         }
1144
1145         after = *i;
1146
1147         if (i == positions.begin ()) {
1148                 /* none before */
1149                 return;
1150         }
1151
1152         --i;
1153         before = *i;
1154 }
1155
1156 Location*
1157 Locations::session_range_location () const
1158 {
1159         for (LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1160                 if ((*i)->is_session_range()) {
1161                         return const_cast<Location*> (*i);
1162                 }
1163         }
1164         return 0;
1165 }
1166
1167 Location*
1168 Locations::auto_loop_location () const
1169 {
1170         for (LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1171                 if ((*i)->is_auto_loop()) {
1172                         return const_cast<Location*> (*i);
1173                 }
1174         }
1175         return 0;
1176 }
1177
1178 Location*
1179 Locations::auto_punch_location () const
1180 {
1181         for (LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1182                 if ((*i)->is_auto_punch()) {
1183                         return const_cast<Location*> (*i);
1184                 }
1185         }
1186        return 0;
1187 }
1188
1189 uint32_t
1190 Locations::num_range_markers () const
1191 {
1192         uint32_t cnt = 0;
1193         Glib::Threads::Mutex::Lock lm (lock);
1194         for (LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1195                 if ((*i)->is_range_marker()) {
1196                         ++cnt;
1197                 }
1198         }
1199         return cnt;
1200 }
1201
1202 Location *
1203 Locations::get_location_by_id(PBD::ID id)
1204 {
1205     LocationList::iterator it;
1206     for (it  = locations.begin(); it != locations.end(); ++it)
1207         if (id == (*it)->id())
1208             return *it;
1209
1210     return 0;
1211 }
1212
1213 void
1214 Locations::find_all_between (framepos_t start, framepos_t end, LocationList& ll, Location::Flags flags)
1215 {
1216         Glib::Threads::Mutex::Lock lm (lock);
1217
1218         for (LocationList::const_iterator i = locations.begin(); i != locations.end(); ++i) {
1219                 if ((flags == 0 || (*i)->matches (flags)) &&
1220                     ((*i)->start() >= start && (*i)->end() < end)) {
1221                         ll.push_back (*i);
1222                 }
1223         }
1224 }
1225