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