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