]> git.donarmstrong.com Git - lilypond.git/blob - lily/accidental-engraver.cc
Merge branch 'master' of ssh+git://hanwen@git.sv.gnu.org/srv/git/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--2006 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   Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
372
373   bool as_suggestion = to_boolean (entry->origin_->get_property ("suggestAccidentals"));
374   Grob *a = 0;
375   if (as_suggestion)
376     a = make_suggested_accidental (note, support, entry->origin_engraver_);
377   else
378     a = make_standard_accidental (note, support, entry->origin_engraver_, cautionary);
379
380   if (restore_natural)
381     {
382       if (to_boolean (get_property ("extraNatural")))
383         a->set_property ("restore-first", SCM_BOOL_T);
384     }
385
386   entry->accidental_ = a;
387 }
388
389 Grob *
390 Accidental_engraver::make_standard_accidental (Stream_event *note,
391                                                Grob *note_head,
392                                                Engraver *trans,
393                                                bool cautionary)
394 {
395   (void)note;
396
397   /*
398     We construct the accidentals at the originating Voice
399     level, so that we get the property settings for
400     Accidental from the respective Voice.
401   */
402   Grob *a = 0;
403   if (cautionary)
404     a = trans->make_item ("AccidentalCautionary", note_head->self_scm ());
405   else
406     a = trans->make_item ("Accidental", note_head->self_scm ());
407
408   /*
409     We add the accidentals to the support of the arpeggio,
410     so it is put left of the accidentals.
411   */
412   for (vsize i = 0; i < left_objects_.size (); i++)
413     {
414       if (left_objects_[i]->get_property ("side-axis") == scm_from_int (X_AXIS))
415         Side_position_interface::add_support (left_objects_[i], a);
416     }
417
418   for (vsize i = 0; i < right_objects_.size (); i++)
419     Side_position_interface::add_support (a, right_objects_[i]);
420
421   a->set_parent (note_head, Y_AXIS);
422
423   if (!accidental_placement_)
424     accidental_placement_ = make_item ("AccidentalPlacement",
425                                        a->self_scm ());
426   Accidental_placement::add_accidental (accidental_placement_, a);
427
428   note_head->set_object ("accidental-grob", a->self_scm ());
429   
430   return a;
431 }
432
433 Grob *
434 Accidental_engraver::make_suggested_accidental (Stream_event *note,
435                                                 Grob *note_head,
436                                                 Engraver *trans)
437 {
438   (void) note;
439
440   Grob *a = trans->make_item ("AccidentalSuggestion", note_head->self_scm ());
441
442   Side_position_interface::add_support (a, note_head);
443   if (Grob *stem = unsmob_grob (a->get_object ("stem")))
444     Side_position_interface::add_support (a, stem);
445
446   a->set_parent (note_head, X_AXIS);
447   return a;
448 }
449
450 void
451 Accidental_engraver::finalize ()
452 {
453   last_keysig_ = SCM_EOL;
454 }
455
456 void
457 Accidental_engraver::stop_translation_timestep ()
458 {
459   for (vsize j = ties_.size (); j--;)
460     {
461       Grob *r = Tie::head (ties_[j], RIGHT);
462       for (vsize i = accidentals_.size (); i--;)
463         if (accidentals_[i].head_ == r)
464           {
465             if (Grob *g = accidentals_[i].accidental_)
466               {
467                 g->set_object ("tie", ties_[j]->self_scm ());
468                 accidentals_[i].tied_ = true;
469               }
470             ties_.erase (ties_.begin () + j);
471             break;
472           }
473     }
474
475   for (vsize i = accidentals_.size (); i--;)
476     {
477       int barnum = get_bar_number ();
478
479       Stream_event *note = accidentals_[i].melodic_;
480       Context *origin = accidentals_[i].origin_;
481
482       Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
483       if (!pitch)
484         continue;
485
486       int n = pitch->get_notename ();
487       int o = pitch->get_octave ();
488       Rational a = pitch->get_alteration ();
489       SCM key = scm_cons (scm_from_int (o), scm_from_int (n));
490
491       SCM localsig = SCM_EOL;
492       while (origin
493              && origin->where_defined (ly_symbol2scm ("localKeySignature"), &localsig))
494         {
495           bool change = false;
496           if (accidentals_[i].tied_)
497             {
498               /*
499                 Remember an alteration that is different both from
500                 that of the tied note and of the key signature.
501               */
502               localsig = ly_assoc_prepend_x (localsig, key, scm_cons (ly_symbol2scm ("tied"),
503                                                                       scm_from_int (barnum)));
504
505               change = true;
506             }
507           else
508             {
509               /*
510                 not really really correct if there are more than one
511                 noteheads with the same notename.
512               */
513               localsig = ly_assoc_prepend_x (localsig, key,
514                                            scm_cons (ly_rational2scm (a),
515                                                      scm_from_int (barnum)));
516               change = true;
517             }
518
519           if (change)
520             origin->set_property ("localKeySignature", localsig);
521
522           origin = origin->get_parent_context ();
523         }
524     }
525
526   accidental_placement_ = 0;
527   accidentals_.clear ();
528   left_objects_.clear ();
529   right_objects_.clear ();
530 }
531
532 void
533 Accidental_engraver::acknowledge_rhythmic_head (Grob_info info)
534 {
535   Stream_event *note = info.event_cause ();
536   if (note
537       && (note->in_event_class ("note-event")
538           || note->in_event_class ("trill-span-event")))
539     {
540       /*
541         string harmonics usually don't have accidentals.
542       */
543       if (info.grob ()->get_property ("style") != ly_symbol2scm ("harmonic")
544           || to_boolean (get_property ("harmonicAccidentals")))
545         {
546           Accidental_entry entry;
547           entry.head_ = info.grob ();
548           entry.origin_engraver_ = dynamic_cast<Engraver *> (info.origin_translator ());
549           entry.origin_ = entry.origin_engraver_->context ();
550           entry.melodic_ = note;
551
552           accidentals_.push_back (entry);
553         }
554     }
555 }
556
557 void
558 Accidental_engraver::acknowledge_tie (Grob_info info)
559 {
560   ties_.push_back (dynamic_cast<Spanner *> (info.grob ()));
561 }
562
563 void
564 Accidental_engraver::acknowledge_arpeggio (Grob_info info)
565 {
566   left_objects_.push_back (info.grob ());
567 }
568
569 void
570 Accidental_engraver::acknowledge_finger (Grob_info info)
571 {
572   left_objects_.push_back (info.grob ());
573 }
574
575 void
576 Accidental_engraver::process_music ()
577 {
578   SCM sig = get_property ("keySignature");
579   if (last_keysig_ != sig)
580     update_local_key_signature (sig);
581 }
582
583 ADD_ACKNOWLEDGER (Accidental_engraver, arpeggio);
584 ADD_ACKNOWLEDGER (Accidental_engraver, finger);
585 ADD_ACKNOWLEDGER (Accidental_engraver, rhythmic_head);
586 ADD_ACKNOWLEDGER (Accidental_engraver, tie);
587
588 ADD_TRANSLATOR (Accidental_engraver,
589                 
590                 "Make accidentals.  "
591                 "Catch note heads, ties and notices key-change events.  "
592                 "This engraver usually lives at Staff level, but "
593                 "reads the settings for Accidental at @code{Voice} level, "
594                 "so you can @code{\\override} them at @code{Voice}. ",
595
596                 /* grobs */
597                 "Accidental "
598                 "AccidentalCautionary"
599                 "AccidentalSuggestion",
600
601                 /* props */
602                 "autoAccidentals "
603                 "autoCautionaries "
604                 "internalBarNumber "
605                 "extraNatural "
606                 "harmonicAccidentals "
607                 "localKeySignature ",
608                 "localKeySignature "
609                 );