]> git.donarmstrong.com Git - lilypond.git/blob - lily/context.cc
Issue 3225: Decouple \defaultchild from \accepts list in contexts
[lilypond.git] / lily / context.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 2004--2012 Han-Wen Nienhuys <hanwen@xs4all.nl>
5
6   LilyPond is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   LilyPond is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "context.hh"
21
22 #include "context-def.hh"
23 #include "dispatcher.hh"
24 #include "global-context.hh"
25 #include "international.hh"
26 #include "ly-smobs.icc"
27 #include "main.hh"
28 #include "output-def.hh"
29 #include "profile.hh"
30 #include "program-option.hh"
31 #include "scm-hash.hh"
32 #include "translator-group.hh"
33 #include "warn.hh"
34
35 bool
36 Context::is_removable () const
37 {
38   return context_list_ == SCM_EOL && ! client_count_
39          && !dynamic_cast<Global_context const *> (daddy_context_);
40 }
41
42 void
43 Context::check_removal ()
44 {
45   for (SCM p = context_list_; scm_is_pair (p); p = scm_cdr (p))
46     {
47       Context *ctx = unsmob_context (scm_car (p));
48
49       ctx->check_removal ();
50       if (ctx->is_removable ())
51         {
52           recurse_over_translators (ctx, &Translator::finalize,
53                                     &Translator_group::finalize,
54                                     UP);
55           send_stream_event (ctx, "RemoveContext", 0, 0);
56         }
57     }
58 }
59
60 Context::Context (Context const & /* src */)
61 {
62   assert (false);
63 }
64
65 Scheme_hash_table *
66 Context::properties_dict () const
67 {
68   return Scheme_hash_table::unsmob (properties_scm_);
69 }
70
71 void
72 Context::add_context (Context *child)
73 {
74   context_list_ = ly_append2 (context_list_,
75                               scm_cons (child->self_scm (), SCM_EOL));
76
77   child->daddy_context_ = this;
78   this->events_below_->register_as_listener (child->events_below_);
79 }
80
81 Context::Context ()
82 {
83   daddy_context_ = 0;
84   aliases_ = SCM_EOL;
85   client_count_ = 0;
86   implementation_ = 0;
87   properties_scm_ = SCM_EOL;
88   accepts_list_ = SCM_EOL;
89   default_child_ = SCM_EOL;
90   context_list_ = SCM_EOL;
91   definition_ = SCM_EOL;
92   definition_mods_ = SCM_EOL;
93   event_source_ = 0;
94   events_below_ = 0;
95   ancestor_lookup_ = SCM_UNDEFINED;
96
97   smobify_self ();
98
99   Scheme_hash_table *tab = new Scheme_hash_table;
100   properties_scm_ = tab->unprotect ();
101   event_source_ = new Dispatcher ();
102   event_source_->unprotect ();
103   events_below_ = new Dispatcher ();
104   events_below_->unprotect ();
105 }
106
107 /* TODO:  this shares code with find_create_context ().  */
108 Context *
109 Context::create_unique_context (SCM name, string id, SCM operations)
110 {
111   /*
112     Don't create multiple score contexts.
113   */
114   Global_context *gthis = dynamic_cast<Global_context *> (this);
115   if (gthis && gthis->get_score_context ())
116     return gthis->get_score_context ()->create_unique_context (name, id, operations);
117
118   vector<Context_def *> path = path_to_acceptable_context (name);
119   if (path.size ())
120     {
121       Context *current = this;
122
123       // Iterate through the path and create all of the implicit contexts.
124       for (vsize i = 0; i < path.size (); i++)
125         {
126           SCM ops = SCM_EOL;
127           string id_str = "\\new";
128           if (i == path.size () - 1)
129             {
130               ops = operations;
131               id_str = id;
132             }
133           current = current->create_context (path[i],
134                                              id_str,
135                                              ops);
136         }
137
138       return current;
139     }
140
141   /*
142     Don't go up to Global_context, because global goes down to the
143     Score context
144   */
145   Context *ret = 0;
146   if (daddy_context_ && !dynamic_cast<Global_context *> (daddy_context_))
147     ret = daddy_context_->create_unique_context (name, id, operations);
148   else
149     {
150       warning (_f ("cannot find or create new `%s'",
151                    ly_symbol2string (name).c_str ()));
152       ret = 0;
153     }
154   return ret;
155 }
156
157 Context *
158 Context::find_create_context (SCM n, string id, SCM operations)
159 {
160   /*
161     Don't create multiple score contexts.
162   */
163   Global_context *gthis = dynamic_cast<Global_context *> (this);
164   if (gthis)
165     {
166       if (gthis->get_score_context ())
167         return gthis->get_score_context ()->find_create_context (n, id, operations);
168
169       // Special case: If we use \set Timing.xxx = whatever before
170       // Score is established, the alias of Score to Timing will not
171       // be taken into account.  We check for this particular case
172       // here.  Aliases apart from Score-level ones don't warrant
173       // context creation as they could create unwanted contexts, like
174       // RhythmicVoice instead of Voice.  Creating a Score context,
175       // however, can't really do anything wrong.
176
177       SCM score_name = default_child_context_name ();
178       SCM score_def = find_context_def (get_output_def (), score_name);
179
180       if (Context_def *cd = unsmob_context_def (score_def))
181         {
182           if (cd->is_alias (n))
183             return create_context (cd, id, operations);
184         }
185     }
186
187
188   if (Context *existing = find_context_below (this, n, id))
189     return existing;
190
191   if (n == ly_symbol2scm ("Bottom"))
192     {
193       Context *tg = get_default_interpreter (id);
194       return tg;
195     }
196
197   vector<Context_def *> path = path_to_acceptable_context (n);
198
199   if (path.size ())
200     {
201       Context *current = this;
202
203       // start at 1.  The first one (index 0) will be us.
204       for (vsize i = 0; i < path.size (); i++)
205         {
206           SCM ops = (i == path.size () - 1) ? operations : SCM_EOL;
207
208           string this_id = "";
209           if (i == path.size () - 1)
210             this_id = id;
211
212           current = current->create_context (path[i],
213                                              this_id,
214                                              ops);
215         }
216
217       return current;
218     }
219
220   /*
221     Don't go up to Global_context, because global goes down to the
222     Score context
223   */
224   Context *ret = 0;
225   if (daddy_context_ && !dynamic_cast<Global_context *> (daddy_context_))
226     ret = daddy_context_->find_create_context (n, id, operations);
227   else
228     {
229       warning (_f ("cannot find or create `%s' called `%s'",
230                    ly_symbol2string (n).c_str (), id));
231       ret = 0;
232     }
233   return ret;
234 }
235
236 IMPLEMENT_LISTENER (Context, acknowledge_infant);
237 void
238 Context::acknowledge_infant (SCM sev)
239 {
240   infant_event_ = unsmob_stream_event (sev);
241 }
242
243 IMPLEMENT_LISTENER (Context, set_property_from_event);
244 void
245 Context::set_property_from_event (SCM sev)
246 {
247   Stream_event *ev = unsmob_stream_event (sev);
248
249   SCM sym = ev->get_property ("symbol");
250   if (scm_is_symbol (sym))
251     {
252       SCM val = ev->get_property ("value");
253
254       if (SCM_UNBNDP (val)) {
255         unset_property (sym);
256         return;
257       }
258           
259       bool ok = true;
260       if (val != SCM_EOL)
261         ok = type_check_assignment (sym, val, ly_symbol2scm ("translation-type?"));
262       if (ok)
263         set_property (sym, val);
264     }
265 }
266
267 IMPLEMENT_LISTENER (Context, unset_property_from_event);
268 void
269 Context::unset_property_from_event (SCM sev)
270 {
271   Stream_event *ev = unsmob_stream_event (sev);
272
273   SCM sym = ev->get_property ("symbol");
274   type_check_assignment (sym, SCM_EOL, ly_symbol2scm ("translation-type?"));
275   unset_property (sym);
276 }
277
278 /*
279   Creates a new context from a CreateContext event, and sends an
280   AnnounceNewContext event to this context.
281 */
282 IMPLEMENT_LISTENER (Context, create_context_from_event);
283 void
284 Context::create_context_from_event (SCM sev)
285 {
286   Stream_event *ev = unsmob_stream_event (sev);
287
288   string id = ly_scm2string (ev->get_property ("id"));
289   SCM ops = ev->get_property ("ops");
290   SCM type_scm = ev->get_property ("type");
291   string type = ly_symbol2string (type_scm);
292
293   vector<Context_def *> path = path_to_acceptable_context (type_scm);
294
295   if (path.size () != 1)
296     {
297       programming_error (to_string ("Invalid CreateContext event: Cannot create %s context", type.c_str ()));
298       return;
299     }
300   Context_def *cdef = path[0];
301
302   Context *new_context = cdef->instantiate (ops);
303
304   new_context->id_string_ = id;
305
306   /* Register various listeners:
307       - Make the new context hear events that universally affect contexts
308       - connect events_below etc. properly */
309   /* We want to be the first ones to hear our own events. Therefore, wait
310      before registering events_below_ */
311   new_context->event_source ()->
312   add_listener (GET_LISTENER (new_context->create_context_from_event),
313                 ly_symbol2scm ("CreateContext"));
314   new_context->event_source ()->
315   add_listener (GET_LISTENER (new_context->remove_context),
316                 ly_symbol2scm ("RemoveContext"));
317   new_context->event_source ()->
318   add_listener (GET_LISTENER (new_context->change_parent),
319                 ly_symbol2scm ("ChangeParent"));
320   new_context->event_source ()->
321   add_listener (GET_LISTENER (new_context->set_property_from_event),
322                 ly_symbol2scm ("SetProperty"));
323   new_context->event_source ()->
324   add_listener (GET_LISTENER (new_context->unset_property_from_event),
325                 ly_symbol2scm ("UnsetProperty"));
326
327   new_context->events_below_->register_as_listener (new_context->event_source_);
328   this->add_context (new_context);
329
330   new_context->unprotect ();
331
332   Context_def *td = unsmob_context_def (new_context->definition_);
333
334   /* This cannot move before add_context (), because \override
335      operations require that we are in the hierarchy.  */
336   td->apply_default_property_operations (new_context);
337   apply_property_operations (new_context, ops);
338
339   send_stream_event (this, "AnnounceNewContext", 0,
340                      ly_symbol2scm ("context"), new_context->self_scm (),
341                      ly_symbol2scm ("creator"), sev);
342 }
343
344 vector<Context_def *>
345 Context::path_to_acceptable_context (SCM name) const
346 {
347   // The 'accepts elements in definition_mods_ is a list of ('accepts string),
348   // but the Context_def expects to see elements of the form ('accepts symbol).
349   SCM accepts = SCM_EOL;
350   for (SCM s = definition_mods_; scm_is_pair (s); s = scm_cdr (s))
351     if (scm_caar (s) == ly_symbol2scm ("accepts"))
352       {
353         SCM elt = scm_list_2 (scm_caar (s), scm_string_to_symbol (scm_cadar (s)));
354         accepts = scm_cons (elt, accepts);
355       }
356
357   return unsmob_context_def (definition_)->path_to_acceptable_context (name,
358          get_output_def (),
359          scm_reverse_x (accepts, SCM_EOL));
360
361 }
362
363 Context *
364 Context::create_context (Context_def *cdef,
365                          string id,
366                          SCM ops)
367 {
368   infant_event_ = 0;
369   /* TODO: This is fairly misplaced. We can fix this when we have taken out all
370      iterator specific stuff from the Context class */
371   event_source_->
372   add_listener (GET_LISTENER (acknowledge_infant),
373                 ly_symbol2scm ("AnnounceNewContext"));
374   /* The CreateContext creates a new context, and sends an announcement of the
375      new context through another event. That event will be stored in
376      infant_event_ to create a return value. */
377   send_stream_event (this, "CreateContext", 0,
378                      ly_symbol2scm ("ops"), ops,
379                      ly_symbol2scm ("type"), cdef->get_context_name (),
380                      ly_symbol2scm ("id"), ly_string2scm (id));
381   event_source_->
382   remove_listener (GET_LISTENER (acknowledge_infant),
383                    ly_symbol2scm ("AnnounceNewContext"));
384
385   assert (infant_event_);
386   SCM infant_scm = infant_event_->get_property ("context");
387   Context *infant = unsmob_context (infant_scm);
388
389   if (!infant || infant->get_parent_context () != this)
390     {
391       programming_error ("create_context: can't locate newly created context");
392       return 0;
393     }
394
395   return infant;
396 }
397
398 /*
399   Default child context as a SCM string, or something else if there is
400   none.
401 */
402 SCM
403 Context::default_child_context_name () const
404 {
405   return default_child_;
406 }
407
408 bool
409 Context::is_bottom_context () const
410 {
411   return !scm_is_symbol (default_child_context_name ());
412 }
413
414 Context *
415 Context::get_default_interpreter (string context_id)
416 {
417   if (!is_bottom_context ())
418     {
419       SCM nm = default_child_context_name ();
420       SCM st = find_context_def (get_output_def (), nm);
421
422       string name = ly_symbol2string (nm);
423       Context_def *t = unsmob_context_def (st);
424       if (!t)
425         {
426           warning (_f ("cannot find or create: `%s'", name.c_str ()));
427           t = unsmob_context_def (this->definition_);
428         }
429
430       Context *tg = create_context (t, context_id, SCM_EOL);
431       return tg->get_default_interpreter (context_id);
432     }
433   return this;
434 }
435
436 /*
437   PROPERTIES
438 */
439 Context *
440 Context::where_defined (SCM sym, SCM *value) const
441 {
442 #ifndef NDEBUG
443   if (profile_property_accesses)
444     note_property_access (&context_property_lookup_table, sym);
445 #endif
446
447   if (properties_dict ()->try_retrieve (sym, value))
448     return (Context *)this;
449
450   return (daddy_context_) ? daddy_context_->where_defined (sym, value) : 0;
451 }
452
453 /*
454   return SCM_EOL when not found.
455 */
456 SCM
457 Context::internal_get_property (SCM sym) const
458 {
459 #ifndef NDEBUG
460   if (profile_property_accesses)
461     note_property_access (&context_property_lookup_table, sym);
462 #endif
463
464   SCM val = SCM_EOL;
465   if (properties_dict ()->try_retrieve (sym, &val))
466     return val;
467
468   if (daddy_context_)
469     return daddy_context_->internal_get_property (sym);
470
471   return val;
472 }
473
474 /*
475 Called by the send_stream_event macro. props is a 0-terminated array of
476 properties and corresponding values, interleaved. This method should not
477 be called from any other place than the send_stream_event macro.
478 */
479 void
480 Context::internal_send_stream_event (SCM type, Input *origin, SCM props[])
481 {
482   Stream_event *e = new Stream_event (make_event_class (type), origin);
483   for (int i = 0; props[i]; i += 2)
484     {
485       e->set_property (props[i], props[i + 1]);
486     }
487   event_source_->broadcast (e);
488   e->unprotect ();
489 }
490
491 bool
492 Context::is_alias (SCM sym) const
493 {
494   if (scm_is_eq (sym, ly_symbol2scm ("Bottom")))
495     return is_bottom_context ();
496   if (scm_is_eq (sym, context_name_symbol ()))
497     return true;
498
499   return scm_c_memq (sym, aliases_) != SCM_BOOL_F;
500 }
501
502 void
503 Context::add_alias (SCM sym)
504 {
505   aliases_ = scm_cons (sym, aliases_);
506 }
507
508 /* we don't (yet) instrument context properties */
509 void
510 Context::instrumented_set_property (SCM sym, SCM val, const char *, int, const char *)
511 {
512   internal_set_property (sym, val);
513 }
514
515 void
516 Context::internal_set_property (SCM sym, SCM val)
517 {
518   bool type_check_ok = type_check_assignment (sym, val, ly_symbol2scm ("translation-type?"));
519
520   if (do_internal_type_checking_global)
521     assert (type_check_ok);
522
523   if (type_check_ok)
524     properties_dict ()->set (sym, val);
525 }
526
527 /*
528   TODO: look up to check whether we have inherited var?
529 */
530 void
531 Context::unset_property (SCM sym)
532 {
533   properties_dict ()->remove (sym);
534 }
535
536 IMPLEMENT_LISTENER (Context, change_parent);
537 void
538 Context::change_parent (SCM sev)
539 {
540   Stream_event *ev = unsmob_stream_event (sev);
541   Context *to = unsmob_context (ev->get_property ("context"));
542
543   disconnect_from_parent ();
544   to->add_context (this);
545 }
546
547 /*
548   Die. The next GC sweep should take care of the actual death.
549  */
550 IMPLEMENT_LISTENER (Context, remove_context);
551 void
552 Context::remove_context (SCM)
553 {
554   /* ugh, the translator group should listen to RemoveContext events by itself */
555   Translator_group *impl = implementation ();
556   if (impl)
557     impl->disconnect_from_context ();
558   disconnect_from_parent ();
559 }
560
561 void
562 Context::disconnect_from_parent ()
563 {
564   daddy_context_->events_below_->unregister_as_listener (this->events_below_);
565   daddy_context_->context_list_ = scm_delq_x (this->self_scm (), daddy_context_->context_list_);
566   daddy_context_ = 0;
567 }
568
569 /*
570   ID == "" means accept any ID.
571 */
572 Context *
573 find_context_below (Context *where,
574                     SCM type, string id)
575 {
576   if (where->is_alias (type))
577     {
578       if (id == "" || where->id_string () == id)
579         return where;
580     }
581
582   Context *found = 0;
583   for (SCM s = where->children_contexts ();
584        !found && scm_is_pair (s); s = scm_cdr (s))
585     {
586       Context *tr = unsmob_context (scm_car (s));
587
588       found = find_context_below (tr, type, id);
589     }
590
591   return found;
592 }
593
594 SCM
595 Context::properties_as_alist () const
596 {
597   return properties_dict ()->to_alist ();
598 }
599
600 SCM
601 Context::context_name_symbol () const
602 {
603   Context_def *td = unsmob_context_def (definition_);
604   return td->get_context_name ();
605 }
606
607 string
608 Context::context_name () const
609 {
610   return ly_symbol2string (context_name_symbol ());
611 }
612
613 Context *
614 Context::get_score_context () const
615 {
616   if (daddy_context_)
617     return daddy_context_->get_score_context ();
618   else
619     return 0;
620 }
621
622 SCM
623 Context::make_event_class (SCM event_type)
624 {
625   if (SCM_UNBNDP (ancestor_lookup_))
626     ancestor_lookup_ = get_global_context ()->ancestor_lookup_;
627   return scm_hashq_ref (ancestor_lookup_, event_type, SCM_EOL);
628 }
629
630 Output_def *
631 Context::get_output_def () const
632 {
633   return daddy_context_ ? daddy_context_->get_output_def () : 0;
634 }
635
636 Context::~Context ()
637 {
638 }
639
640 Moment
641 Context::now_mom () const
642 {
643   Context const *p = this;
644   while (p->daddy_context_)
645     p = p->daddy_context_;
646
647   return p->now_mom ();
648 }
649
650 int
651 Context::print_smob (SCM s, SCM port, scm_print_state *)
652 {
653   Context *sc = (Context *) SCM_CELL_WORD_1 (s);
654
655   scm_puts ("#<", port);
656   scm_puts (sc->class_name (), port);
657   if (Context_def *d = unsmob_context_def (sc->definition_))
658     {
659       scm_puts (" ", port);
660       scm_display (d->get_context_name (), port);
661     }
662
663   if (!sc->id_string_.empty ())
664     {
665       scm_puts ("=", port);
666       scm_puts (sc->id_string_.c_str (), port);
667     }
668
669   scm_puts (" ", port);
670
671   scm_display (sc->context_list_, port);
672   scm_puts (" >", port);
673
674   return 1;
675 }
676
677 SCM
678 Context::mark_smob (SCM sm)
679 {
680   Context *me = (Context *) SCM_CELL_WORD_1 (sm);
681
682   scm_gc_mark (me->context_list_);
683   scm_gc_mark (me->aliases_);
684   scm_gc_mark (me->definition_);
685   scm_gc_mark (me->definition_mods_);
686   scm_gc_mark (me->properties_scm_);
687   scm_gc_mark (me->accepts_list_);
688   scm_gc_mark (me->default_child_);
689
690   if (me->implementation_)
691     scm_gc_mark (me->implementation_->self_scm ());
692
693   if (me->event_source_)
694     scm_gc_mark (me->event_source_->self_scm ());
695
696   if (me->events_below_)
697     scm_gc_mark (me->events_below_->self_scm ());
698
699   scm_gc_mark (me->ancestor_lookup_);
700
701   return me->properties_scm_;
702 }
703
704 IMPLEMENT_SMOBS (Context);
705 IMPLEMENT_DEFAULT_EQUAL_P (Context);
706 IMPLEMENT_TYPE_P (Context, "ly:context?");
707
708 Global_context *
709 Context::get_global_context () const
710 {
711   if (dynamic_cast<Global_context *> ((Context *) this))
712     return dynamic_cast<Global_context *> ((Context *) this);
713
714   if (daddy_context_)
715     return daddy_context_->get_global_context ();
716
717   programming_error ("no Global context");
718   return 0;
719 }
720
721 Context *
722 Context::get_parent_context () const
723 {
724   return daddy_context_;
725 }
726
727 /*
728   Ugh. Where to put this?
729 */
730 Rational
731 measure_length (Context const *context)
732 {
733   SCM l = context->get_property ("measureLength");
734   Rational length (1);
735   if (unsmob_moment (l))
736     length = unsmob_moment (l)->main_part_;
737   return length;
738 }
739
740 Moment
741 measure_position (Context const *context)
742 {
743   SCM sm = context->get_property ("measurePosition");
744
745   Moment m = 0;
746   if (unsmob_moment (sm))
747     {
748       m = *unsmob_moment (sm);
749
750       if (m.main_part_ < Rational (0))
751         {
752           Rational length (measure_length (context));
753           while (m.main_part_ < Rational (0))
754             m.main_part_ += length;
755         }
756     }
757
758   return m;
759 }
760
761 /* Finds the measure position after a note of length DUR that
762    begins at the current measure position. */
763 Moment
764 measure_position (Context const *context, Duration const *dur)
765 {
766   Moment pos = measure_position (context);
767   Rational dur_length = dur ? dur->get_length () : Rational (0);
768
769   Moment end_pos = pos.grace_part_ < Rational (0)
770                    ? Moment (pos.main_part_, pos.grace_part_ + dur_length)
771                    : Moment (pos.main_part_ + dur_length, 0);
772
773   return end_pos;
774 }
775
776 int
777 measure_number (Context const *context)
778 {
779   SCM barnum = context->get_property ("internalBarNumber");
780   SCM smp = context->get_property ("measurePosition");
781
782   int bn = robust_scm2int (barnum, 0);
783   Moment mp = robust_scm2moment (smp, Moment (0));
784   if (mp.main_part_ < Rational (0))
785     bn--;
786
787   return bn;
788 }
789
790 void
791 set_context_property_on_children (Context *trans, SCM sym, SCM val)
792 {
793   trans->set_property (sym, ly_deep_copy (val));
794   for (SCM p = trans->children_contexts (); scm_is_pair (p); p = scm_cdr (p))
795     {
796       Context *trg = unsmob_context (scm_car (p));
797       set_context_property_on_children (trg, sym, ly_deep_copy (val));
798     }
799 }
800
801 bool
802 melisma_busy (Context *tr)
803 {
804   SCM melisma_properties = tr->get_property ("melismaBusyProperties");
805   bool busy = false;
806
807   for (; !busy && scm_is_pair (melisma_properties);
808        melisma_properties = scm_cdr (melisma_properties))
809     busy = busy || to_boolean (tr->internal_get_property (scm_car (melisma_properties)));
810
811   return busy;
812 }
813
814 bool
815 check_repeat_count_visibility (Context const *context, SCM count)
816 {
817   SCM proc = context->get_property ("repeatCountVisibility");
818   return (ly_is_procedure (proc)
819           && to_boolean (scm_call_2 (proc,
820                                      count,
821                                      context->self_scm ())));
822 }