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