]> git.donarmstrong.com Git - lilypond.git/blob - lily/accidental-engraver.cc
37398d3d4d274b2558aac3a7b36b04e76ee01d13
[lilypond.git] / lily / accidental-engraver.cc
1 /*
2   accidental-engraver.cc -- implement Accidental_engraver
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1997--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
7   Modified 2001--2002 by Rune Zedeler <rz@daimi.au.dk>
8 */
9
10 #include "accidental-placement.hh"
11 #include "arpeggio.hh"
12 #include "context.hh"
13 #include "duration.hh"
14 #include "engraver.hh"
15 #include "international.hh"
16 #include "item.hh"
17 #include "pitch.hh"
18 #include "protected-scm.hh"
19 #include "rhythmic-head.hh"
20 #include "separation-item.hh"
21 #include "side-position-interface.hh"
22 #include "spanner.hh"
23 #include "stream-event.hh"
24 #include "tie.hh"
25 #include "warn.hh"
26
27 #include "translator.icc"
28
29 class Accidental_entry
30 {
31 public:
32   bool done_;
33   Stream_event *melodic_;
34   Grob *accidental_;
35   Context *origin_;
36   Engraver *origin_engraver_;
37   Grob *head_;
38   bool tied_;
39
40   Accidental_entry ();
41 };
42
43 Accidental_entry::Accidental_entry ()
44 {
45   tied_ = false;
46   done_ = false;
47   melodic_ = 0;
48   accidental_ = 0;
49   origin_ = 0;
50   head_ = 0;
51 }
52
53 class Accidental_engraver : public Engraver
54 {
55   void update_local_key_signature (SCM new_signature);
56   void create_accidental (Accidental_entry *entry, bool, bool);
57   Grob *make_standard_accidental (Stream_event *note, Grob *note_head, Engraver *trans, bool);
58   Grob *make_suggested_accidental (Stream_event *note, Grob *note_head, Engraver *trans);
59
60 protected:
61   TRANSLATOR_DECLARATIONS (Accidental_engraver);
62   void process_music ();
63
64   void acknowledge_tie (Grob_info);
65   void acknowledge_arpeggio (Grob_info);
66   void acknowledge_rhythmic_head (Grob_info);
67   void acknowledge_finger (Grob_info);
68   void acknowledge_note_column (Grob_info);
69
70   void stop_translation_timestep ();
71   void process_acknowledged ();
72   
73   virtual void finalize ();
74   virtual void derived_mark () const;
75
76 public:
77   SCM last_keysig_;
78
79   vector<Grob*> left_objects_;
80   vector<Grob*> right_objects_;
81
82   Grob *accidental_placement_;
83
84   vector<Accidental_entry> accidentals_;
85   vector<Spanner*> ties_;
86   vector<Grob*> note_columns_;
87 };
88
89 /*
90   localKeySignature is changed at runtime, which means that references
91   in grobs should always store ly_deep_copy ()s of those.
92 */
93
94
95 Accidental_engraver::Accidental_engraver ()
96 {
97   accidental_placement_ = 0;
98   last_keysig_ = SCM_EOL;
99 }
100
101 void
102 Accidental_engraver::derived_mark () const
103 {
104   scm_gc_mark (last_keysig_);
105 }
106
107 void
108 Accidental_engraver::update_local_key_signature (SCM new_sig)
109 {
110   last_keysig_ = new_sig;
111   set_context_property_on_children (context (),
112                                     ly_symbol2scm ("localKeySignature"),
113                                     new_sig);
114
115   Context *trans = context ()->get_parent_context ();
116
117   /* Reset parent contexts so that e.g. piano-accidentals won't remember old
118      cross-staff accidentals after key-sig-changes */
119
120   SCM val;
121   while (trans && trans->where_defined (ly_symbol2scm ("localKeySignature"), &val)==trans)
122     {
123       trans->set_property ("localKeySignature", ly_deep_copy (last_keysig_));
124       trans = trans->get_parent_context ();
125     }
126 }
127
128
129 /** Calculate the number of accidentals on basis of the current local key
130     sig (passed as argument)
131
132     * First check step+octave (taking into account barnumbers if necessary).
133
134     * Then check the global signature (only step).
135
136     Return number of accidentals (0, 1 or 2).  */
137
138 static bool
139 recent_enough (int bar_number, SCM alteration_def, SCM laziness)
140 {
141   if (scm_is_number (alteration_def)
142       || laziness == SCM_BOOL_T)
143     return true;
144
145   return (bar_number <= scm_to_int (scm_cadr (alteration_def)) + scm_to_int (laziness));
146 }
147
148 static Rational
149 extract_alteration (SCM alteration_def)
150 {
151   if (scm_is_number (alteration_def))
152     return ly_scm2rational (alteration_def);
153   else if (scm_is_pair (alteration_def))
154     return ly_scm2rational (scm_car (alteration_def));
155   else if (alteration_def == SCM_BOOL_F)
156     return Rational (0);
157   else
158     assert (0);
159   return Rational (0);
160 }
161
162 bool
163 is_tied (SCM alteration_def)
164 {
165   SCM tied = ly_symbol2scm ("tied");
166   return (alteration_def == tied
167           || (scm_is_pair (alteration_def) && scm_car (alteration_def) == tied));
168 }
169
170 struct Accidental_result
171 {
172   bool need_acc;
173   bool need_restore;
174
175   Accidental_result ()
176   {
177     need_restore = need_acc = false;
178   }
179
180   Accidental_result (bool restore, bool acc)
181   {
182     need_restore = restore;
183     need_acc = acc;
184   }
185
186   Accidental_result (SCM scm)
187   {
188     need_restore = to_boolean (scm_car (scm));
189     need_acc = to_boolean (scm_cdr (scm));
190   }
191
192   int score () const
193   {
194     return need_acc ? 1 : 0
195       + need_restore ? 1 : 0;
196   }
197 };
198
199 Accidental_result
200 check_pitch_against_signature (SCM key_signature, Pitch const &pitch,
201                                int bar_number, SCM laziness, bool ignore_octave)
202 {
203   Accidental_result result;
204   int n = pitch.get_notename ();
205   int o = pitch.get_octave ();
206
207   SCM previous_alteration = SCM_BOOL_F;
208
209   SCM from_same_octave = ly_assoc_get (scm_cons (scm_from_int (o),
210                                                  scm_from_int (n)), key_signature, SCM_BOOL_F);
211   SCM from_key_signature = ly_assoc_get (scm_from_int (n), key_signature, SCM_BOOL_F);
212   SCM from_other_octaves = SCM_BOOL_F;
213   for (SCM s = key_signature; scm_is_pair (s); s = scm_cdr (s))
214     {
215       SCM entry = scm_car (s);
216       if (scm_is_pair (scm_car (entry))
217           && scm_cdar (entry) == scm_from_int (n))
218         {
219           from_other_octaves = scm_cdr (entry);
220           break;
221         }
222     }
223
224   if (!ignore_octave
225       && from_same_octave != SCM_BOOL_F
226       && recent_enough (bar_number, from_same_octave, laziness))
227     previous_alteration = from_same_octave;
228   else if (ignore_octave
229            && from_other_octaves != SCM_BOOL_F
230            && recent_enough (bar_number, from_other_octaves, laziness))
231     previous_alteration = from_other_octaves;
232   else if (from_key_signature != SCM_BOOL_F)
233     previous_alteration = from_key_signature;
234
235   if (is_tied (previous_alteration))
236     {
237       result.need_acc = true;
238     }
239   else
240     {
241       Rational prev = extract_alteration (previous_alteration);
242       Rational alter = pitch.get_alteration ();
243
244       if (alter != prev)
245         {
246           result.need_acc = true;
247           if (alter.sign ()
248               && (alter.abs () < prev.abs ()
249                   || (prev * alter).sign () < 0))
250             result.need_restore = true;
251         }
252     }
253
254   return result;
255 }
256
257 // TODO: consider moving check_pitch_against_signature to SCM (in which case
258 // we can delete this function).
259 LY_DEFINE (ly_find_accidentals_simple, "ly:find-accidentals-simple", 5, 0, 0,
260            (SCM keysig, SCM pitch_scm, SCM barnum, SCM laziness, SCM octaveness ),
261            "Checks the need for an accidental and a @q{restore} accidental against a"
262            " key signature.  The @var{laziness} is the number of bars for which reminder"
263            " accidentals are used (ie. if @var{laziness} is zero, we only cancel accidentals"
264            " in the same bar; if @var{laziness} is three, we cancel accidentals up to three"
265            " bars after they first appear.  @var{octaveness} is either"
266            " @code{'same-octave} or @code{'any-octave} and it specifies whether"
267            " accidentals should be canceled in different octaves.")
268 {
269   LY_ASSERT_TYPE (unsmob_pitch, pitch_scm, 2);
270   LY_ASSERT_TYPE (scm_is_integer, barnum, 3);
271   LY_ASSERT_TYPE (ly_is_symbol, octaveness, 5);
272
273   bool symbol_ok = octaveness == ly_symbol2scm ("any-octave") ||
274     octaveness == ly_symbol2scm ("same-octave");
275
276   SCM_ASSERT_TYPE (symbol_ok, octaveness, SCM_ARG5, __FUNCTION__, "'any-octave or 'same-octave");
277
278   Pitch *pitch = unsmob_pitch (pitch_scm);
279
280   int bar_number = scm_to_int (barnum);
281   bool ignore_octave = ly_symbol2scm ("any-octave") == octaveness; 
282   Accidental_result result = check_pitch_against_signature (keysig, *pitch, bar_number,
283                                                             laziness, ignore_octave);
284
285   return scm_cons (scm_from_bool (result.need_restore), scm_from_bool (result.need_acc));
286 }
287
288 static
289 Accidental_result
290 check_pitch_against_rules (Pitch const &pitch, Context *origin,
291                            SCM rules, int bar_number, SCM measurepos)
292 {
293   Accidental_result result;
294   SCM pitch_scm = pitch.smobbed_copy ();
295   SCM barnum_scm = scm_from_int (bar_number);
296
297   if (scm_is_pair (rules) && !scm_is_symbol (scm_car (rules)))
298     warning (_f ("accidental typesetting list must begin with context-name: %s",
299                  ly_scm2string (scm_car (rules)).c_str ()));
300
301   for (; scm_is_pair (rules) && origin;
302        rules = scm_cdr (rules))
303     {
304       SCM rule = scm_car (rules);
305       if (ly_is_procedure (rule))
306         {
307           SCM rule_result_scm = scm_call_4 (rule, origin->self_scm (),
308                                             pitch_scm, barnum_scm, measurepos);
309
310           Accidental_result rule_result (rule_result_scm);
311
312           result.need_acc |= rule_result.need_acc;
313           result.need_restore |= rule_result.need_restore;
314         }
315
316       /* if symbol then it is a context name.  Scan parent contexts to
317          find it. */
318       else if (scm_is_symbol (rule))
319         {
320           Context *dad = origin;
321           while (dad && !dad->is_alias (rule))
322             dad = dad->get_parent_context ();
323
324           if (dad)
325             origin = dad;
326         }
327       else
328         warning (_f ("procedure or context-name expected for accidental rule, found %s",
329                      print_scm_val (rule).c_str ()));
330     }
331
332   return result;
333 }
334
335 void
336 Accidental_engraver::process_acknowledged ()
337 {
338   if (accidentals_.size () && !accidentals_.back ().done_)
339     {
340       SCM accidental_rules = get_property ("autoAccidentals");
341       SCM cautionary_rules = get_property ("autoCautionaries");
342       SCM measure_position = get_property ("measurePosition");
343       int barnum = measure_number (context());
344
345       for (vsize i = 0; i < accidentals_.size (); i++)
346         {
347           if (accidentals_[i].done_)
348             continue;
349           accidentals_[i].done_ = true;
350
351           Stream_event *note = accidentals_[i].melodic_;
352           Context *origin = accidentals_[i].origin_;
353
354           Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
355           if (!pitch)
356             continue;
357
358           Accidental_result acc = check_pitch_against_rules (*pitch, origin, accidental_rules,
359                                                              barnum, measure_position);
360           Accidental_result caut = check_pitch_against_rules (*pitch, origin, cautionary_rules,
361                                                               barnum, measure_position);
362
363           bool cautionary = to_boolean (note->get_property ("cautionary"));
364           if (caut.score () > acc.score ())
365             {
366               acc.need_acc |= caut.need_acc; 
367               acc.need_restore |= caut.need_restore; 
368
369               cautionary = true;
370             }
371
372           bool forced = to_boolean (note->get_property ("force-accidental"));
373           if (!acc.need_acc && forced)
374             acc.need_acc = true;
375
376           /* Cannot look for ties: it's not guaranteed that they reach
377              us before the notes. */
378           if (!note->in_event_class ("trill-span-event"))
379             {
380               if (acc.need_acc)       
381                 create_accidental (&accidentals_[i], acc.need_restore, cautionary);
382
383               if (forced || cautionary)
384                 accidentals_[i].accidental_->set_property ("forced", SCM_BOOL_T);
385             }
386         }
387     }
388 }
389
390 void
391 Accidental_engraver::create_accidental (Accidental_entry *entry,
392                                         bool restore_natural,
393                                         bool cautionary)
394 {
395   Stream_event *note = entry->melodic_;
396   Grob *support = entry->head_;
397   bool as_suggestion = to_boolean (entry->origin_->get_property ("suggestAccidentals"));
398   Grob *a = 0;
399   if (as_suggestion)
400     a = make_suggested_accidental (note, support, entry->origin_engraver_);
401   else
402     a = make_standard_accidental (note, support, entry->origin_engraver_, cautionary);
403
404   if (restore_natural)
405     {
406       if (to_boolean (get_property ("extraNatural")))
407         a->set_property ("restore-first", SCM_BOOL_T);
408     }
409
410   entry->accidental_ = a;
411 }
412
413 Grob *
414 Accidental_engraver::make_standard_accidental (Stream_event *note,
415                                                Grob *note_head,
416                                                Engraver *trans,
417                                                bool cautionary)
418 {
419   (void)note;
420
421   /*
422     We construct the accidentals at the originating Voice
423     level, so that we get the property settings for
424     Accidental from the respective Voice.
425   */
426   Grob *a = 0;
427   if (cautionary)
428     a = trans->make_item ("AccidentalCautionary", note_head->self_scm ());
429   else
430     a = trans->make_item ("Accidental", note_head->self_scm ());
431
432   /*
433     We add the accidentals to the support of the arpeggio,
434     so it is put left of the accidentals.
435   */
436   for (vsize i = 0; i < left_objects_.size (); i++)
437     {
438       if (left_objects_[i]->get_property ("side-axis") == scm_from_int (X_AXIS))
439         Side_position_interface::add_support (left_objects_[i], a);
440     }
441
442   for (vsize i = 0; i < right_objects_.size (); i++)
443     Side_position_interface::add_support (a, right_objects_[i]);
444
445   a->set_parent (note_head, Y_AXIS);
446
447   if (!accidental_placement_)
448     accidental_placement_ = make_item ("AccidentalPlacement",
449                                        a->self_scm ());
450   Accidental_placement::add_accidental (accidental_placement_, a);
451
452   note_head->set_object ("accidental-grob", a->self_scm ());
453   
454   return a;
455 }
456
457 Grob *
458 Accidental_engraver::make_suggested_accidental (Stream_event *note,
459                                                 Grob *note_head,
460                                                 Engraver *trans)
461 {
462   (void) note;
463
464   Grob *a = trans->make_item ("AccidentalSuggestion", note_head->self_scm ());
465
466   Side_position_interface::add_support (a, note_head);
467   if (Grob *stem = unsmob_grob (a->get_object ("stem")))
468     Side_position_interface::add_support (a, stem);
469
470   a->set_parent (note_head, X_AXIS);
471   return a;
472 }
473
474 void
475 Accidental_engraver::finalize ()
476 {
477   last_keysig_ = SCM_EOL;
478 }
479
480 void
481 Accidental_engraver::stop_translation_timestep ()
482 {
483   for (vsize j = ties_.size (); j--;)
484     {
485       Grob *r = Tie::head (ties_[j], RIGHT);
486       for (vsize i = accidentals_.size (); i--;)
487         if (accidentals_[i].head_ == r)
488           {
489             if (Grob *g = accidentals_[i].accidental_)
490               {
491                 g->set_object ("tie", ties_[j]->self_scm ());
492                 accidentals_[i].tied_ = true;
493               }
494             ties_.erase (ties_.begin () + j);
495             break;
496           }
497     }
498
499   for (vsize i = accidentals_.size (); i--;)
500     {      
501       Stream_event *note = accidentals_[i].melodic_;
502       Context *origin = accidentals_[i].origin_;
503
504       int barnum = measure_number (origin);
505
506       Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
507       if (!pitch)
508         continue;
509
510       int n = pitch->get_notename ();
511       int o = pitch->get_octave ();
512       Rational a = pitch->get_alteration ();
513       SCM key = scm_cons (scm_from_int (o), scm_from_int (n));
514
515       Moment end_mp = measure_position (context (),
516                                         unsmob_duration (note->get_property ("duration")));
517       SCM position = scm_cons (scm_from_int (barnum), end_mp.smobbed_copy ());
518
519       SCM localsig = SCM_EOL;
520       while (origin
521              && origin->where_defined (ly_symbol2scm ("localKeySignature"), &localsig))
522         {
523           bool change = false;
524           if (accidentals_[i].tied_
525               && !(to_boolean (accidentals_[i].accidental_->get_property ("forced"))))
526             {
527               /*
528                 Remember an alteration that is different both from
529                 that of the tied note and of the key signature.
530               */
531               localsig = ly_assoc_prepend_x (localsig, key,scm_cons (ly_symbol2scm ("tied"),
532                                                                      position));
533
534               change = true;
535             }
536           else
537             {
538               /*
539                 not really really correct if there are more than one
540                 noteheads with the same notename.
541               */
542               localsig = ly_assoc_prepend_x (localsig, key,
543                                              scm_cons (ly_rational2scm (a),
544                                                        position));
545               change = true;
546             }
547
548           if (change)
549             origin->set_property ("localKeySignature", localsig);
550
551           origin = origin->get_parent_context ();
552         }
553     }
554
555   if (accidental_placement_)
556     for (vsize i = 0; i < note_columns_.size (); i++)
557       Separation_item::add_conditional_item (note_columns_[i], accidental_placement_);
558
559   accidental_placement_ = 0;
560   accidentals_.clear ();
561   left_objects_.clear ();
562   right_objects_.clear ();
563 }
564
565 void
566 Accidental_engraver::acknowledge_rhythmic_head (Grob_info info)
567 {
568   Stream_event *note = info.event_cause ();
569   if (note
570       && (note->in_event_class ("note-event")
571           || note->in_event_class ("trill-span-event")))
572     {
573       /*
574         string harmonics usually don't have accidentals.
575       */
576       if (info.grob ()->get_property ("style") != ly_symbol2scm ("harmonic")
577           || to_boolean (get_property ("harmonicAccidentals")))
578         {
579           Accidental_entry entry;
580           entry.head_ = info.grob ();
581           entry.origin_engraver_ = dynamic_cast<Engraver *> (info.origin_translator ());
582           entry.origin_ = entry.origin_engraver_->context ();
583           entry.melodic_ = note;
584
585           accidentals_.push_back (entry);
586         }
587     }
588 }
589
590 void
591 Accidental_engraver::acknowledge_tie (Grob_info info)
592 {
593   ties_.push_back (dynamic_cast<Spanner *> (info.grob ()));
594 }
595
596 void
597 Accidental_engraver::acknowledge_note_column (Grob_info info)
598 {
599   note_columns_.push_back (info.grob ());
600 }
601
602 void
603 Accidental_engraver::acknowledge_arpeggio (Grob_info info)
604 {
605   left_objects_.push_back (info.grob ());
606 }
607
608 void
609 Accidental_engraver::acknowledge_finger (Grob_info info)
610 {
611   left_objects_.push_back (info.grob ());
612 }
613
614 void
615 Accidental_engraver::process_music ()
616 {
617   SCM sig = get_property ("keySignature");
618   if (last_keysig_ != sig)
619     update_local_key_signature (sig);
620 }
621
622 ADD_ACKNOWLEDGER (Accidental_engraver, arpeggio);
623 ADD_ACKNOWLEDGER (Accidental_engraver, finger);
624 ADD_ACKNOWLEDGER (Accidental_engraver, rhythmic_head);
625 ADD_ACKNOWLEDGER (Accidental_engraver, tie);
626 ADD_ACKNOWLEDGER (Accidental_engraver, note_column);
627
628 ADD_TRANSLATOR (Accidental_engraver,
629                 /* doc */
630                 "Make accidentals."
631                 "  Catch note heads, ties and notices key-change events."
632                 "  This engraver usually lives at Staff level, but"
633                 " reads the settings for Accidental at @code{Voice} level,"
634                 " so you can @code{\\override} them at @code{Voice}.",
635
636                 /* create */
637                 "Accidental "
638                 "AccidentalCautionary "
639                 "AccidentalPlacement "
640                 "AccidentalSuggestion ",
641
642                 /* read */
643                 "autoAccidentals "
644                 "autoCautionaries "
645                 "internalBarNumber "
646                 "extraNatural "
647                 "harmonicAccidentals "
648                 "keySignature "
649                 "localKeySignature ",
650
651                 /* write */
652                 "localKeySignature "
653                 );