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