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