]> git.donarmstrong.com Git - lilypond.git/blob - lily/accidental-engraver.cc
Merge branch 'master' of git://git.sv.gnu.org/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   int get_bar_number ();
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_cdr (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     need_restore = need_acc = false;
177   }
178
179   int score () const {
180     return need_acc ? 1 : 0
181       + need_restore ? 1 : 0;
182   }
183 };
184
185 Accidental_result
186 check_pitch_against_signature (SCM key_signature, Pitch const &pitch,
187                                int bar_number, SCM laziness, bool ignore_octave)
188 {
189   Accidental_result result;
190   int n = pitch.get_notename ();
191   int o = pitch.get_octave ();
192
193   SCM previous_alteration = SCM_BOOL_F;
194
195   SCM from_same_octave = ly_assoc_get (scm_cons (scm_from_int (o),
196                                                  scm_from_int (n)), key_signature, SCM_BOOL_F);
197   SCM from_key_signature = ly_assoc_get (scm_from_int (n), key_signature, SCM_BOOL_F);
198   SCM from_other_octaves = SCM_BOOL_F;
199   for (SCM s = key_signature; scm_is_pair (s); s = scm_cdr (s))
200     {
201       SCM entry = scm_car (s);
202       if (scm_is_pair (scm_car (entry))
203           && scm_cdar (entry) == scm_from_int (n))
204         {
205           from_other_octaves = scm_cdr (entry);
206           break;
207         }
208     }
209
210   if (!ignore_octave
211       && from_same_octave != SCM_BOOL_F
212       && recent_enough (bar_number, from_same_octave, laziness))
213     previous_alteration = from_same_octave;
214   else if (ignore_octave
215            && from_other_octaves != SCM_BOOL_F
216            && recent_enough (bar_number, from_other_octaves, laziness))
217     previous_alteration = from_other_octaves;
218   else if (from_key_signature != SCM_BOOL_F)
219     previous_alteration = from_key_signature;
220
221   if (is_tied (previous_alteration))
222     {
223       result.need_acc = true;
224     }
225   else
226     {
227       Rational prev = extract_alteration (previous_alteration);
228       Rational alter = pitch.get_alteration ();
229
230       if (alter != prev)
231         {
232           result.need_acc = true;
233           if (alter.sign ()
234               && (alter.abs () < prev.abs ()
235                   || (prev * alter).sign () < 0))
236             result.need_restore = true;
237         }
238     }
239
240   return result;
241 }
242
243 static
244 Accidental_result
245 check_pitch_against_rules (Pitch const &pitch, Context *origin,
246                                  SCM rules, int bar_number)
247 {
248   Accidental_result result;
249   if (scm_is_pair (rules) && !scm_is_symbol (scm_car (rules)))
250     warning (_f ("accidental typesetting list must begin with context-name: %s",
251                  ly_scm2string (scm_car (rules)).c_str ()));
252
253   for (; scm_is_pair (rules) && origin;
254        rules = scm_cdr (rules))
255     {
256       SCM rule = scm_car (rules);
257       if (scm_is_pair (rule))
258         {
259           SCM type = scm_car (rule);
260           SCM laziness = scm_cdr (rule);
261           SCM localsig = origin->get_property ("localKeySignature");
262
263           bool same_octave
264             = (ly_symbol2scm ("same-octave") == type);
265           bool any_octave
266             = (ly_symbol2scm ("any-octave") == type);
267
268           if (same_octave || any_octave)
269             {
270               Accidental_result rule_result = check_pitch_against_signature
271                 (localsig, pitch, bar_number, laziness, any_octave);
272
273               result.need_acc |= rule_result.need_acc;
274               result.need_restore |= rule_result.need_restore;
275             }
276           else
277             warning (_f ("ignoring unknown accidental rule: %s",
278                          ly_symbol2string (type).c_str ()));
279         }
280
281       /* if symbol then it is a context name.  Scan parent contexts to
282          find it. */
283       else if (scm_is_symbol (rule))
284         {
285           Context *dad = origin;
286           while (dad && !dad->is_alias (rule))
287             dad = dad->get_parent_context ();
288
289           if (dad)
290             origin = dad;
291         }
292       else
293         warning (_f ("pair or context-name expected for accidental rule, found %s",
294                      ly_scm2string (rule).c_str ()));
295     }
296
297   return result;
298 }
299
300 int
301 Accidental_engraver::get_bar_number ()
302 {
303   SCM barnum = get_property ("internalBarNumber");
304   SCM smp = get_property ("measurePosition");
305
306   int bn = robust_scm2int (barnum, 0);
307
308   Moment mp = robust_scm2moment (smp, Moment (0));
309   if (mp.main_part_ < Rational (0))
310     bn--;
311
312   return bn;
313 }
314
315 void
316 Accidental_engraver::process_acknowledged ()
317 {
318   if (accidentals_.size () && !accidentals_.back ().done_)
319     {
320       SCM accidental_rules = get_property ("autoAccidentals");
321       SCM cautionary_rules = get_property ("autoCautionaries");
322       int barnum = get_bar_number ();
323
324       for (vsize i = 0; i < accidentals_.size (); i++)
325         {
326           if (accidentals_[i].done_)
327             continue;
328           accidentals_[i].done_ = true;
329
330           Stream_event *note = accidentals_[i].melodic_;
331           Context *origin = accidentals_[i].origin_;
332
333           Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
334           if (!pitch)
335             continue;
336
337           Accidental_result acc = check_pitch_against_rules (*pitch, origin,
338                                                              accidental_rules, barnum);
339           Accidental_result caut = check_pitch_against_rules (*pitch, origin,
340                                                               cautionary_rules, barnum);
341
342           bool cautionary = to_boolean (note->get_property ("cautionary"));
343           if (caut.score () > acc.score ())
344             {
345               acc.need_acc |= caut.need_acc; 
346               acc.need_restore |= caut.need_restore; 
347
348               cautionary = true;
349             }
350
351           bool forced = to_boolean (note->get_property ("force-accidental"));
352           if (!acc.need_acc && forced)
353             acc.need_acc = true;
354
355           /* Cannot look for ties: it's not guaranteed that they reach
356              us before the notes. */
357           if (acc.need_acc
358               && !note->in_event_class ("trill-span-event"))
359             create_accidental (&accidentals_[i], acc.need_restore, cautionary);
360
361           if (forced || cautionary)
362             accidentals_[i].accidental_->set_property ("forced", SCM_BOOL_T);
363         }
364     }
365 }
366
367 void
368 Accidental_engraver::create_accidental (Accidental_entry *entry,
369                                         bool restore_natural,
370                                         bool cautionary)
371 {
372   Stream_event *note = entry->melodic_;
373   Grob *support = entry->head_;
374   bool as_suggestion = to_boolean (entry->origin_->get_property ("suggestAccidentals"));
375   Grob *a = 0;
376   if (as_suggestion)
377     a = make_suggested_accidental (note, support, entry->origin_engraver_);
378   else
379     a = make_standard_accidental (note, support, entry->origin_engraver_, cautionary);
380
381   if (restore_natural)
382     {
383       if (to_boolean (get_property ("extraNatural")))
384         a->set_property ("restore-first", SCM_BOOL_T);
385     }
386
387   entry->accidental_ = a;
388 }
389
390 Grob *
391 Accidental_engraver::make_standard_accidental (Stream_event *note,
392                                                Grob *note_head,
393                                                Engraver *trans,
394                                                bool cautionary)
395 {
396   (void)note;
397
398   /*
399     We construct the accidentals at the originating Voice
400     level, so that we get the property settings for
401     Accidental from the respective Voice.
402   */
403   Grob *a = 0;
404   if (cautionary)
405     a = trans->make_item ("AccidentalCautionary", note_head->self_scm ());
406   else
407     a = trans->make_item ("Accidental", note_head->self_scm ());
408
409   /*
410     We add the accidentals to the support of the arpeggio,
411     so it is put left of the accidentals.
412   */
413   for (vsize i = 0; i < left_objects_.size (); i++)
414     {
415       if (left_objects_[i]->get_property ("side-axis") == scm_from_int (X_AXIS))
416         Side_position_interface::add_support (left_objects_[i], a);
417     }
418
419   for (vsize i = 0; i < right_objects_.size (); i++)
420     Side_position_interface::add_support (a, right_objects_[i]);
421
422   a->set_parent (note_head, Y_AXIS);
423
424   if (!accidental_placement_)
425     accidental_placement_ = make_item ("AccidentalPlacement",
426                                        a->self_scm ());
427   Accidental_placement::add_accidental (accidental_placement_, a);
428
429   note_head->set_object ("accidental-grob", a->self_scm ());
430   
431   return a;
432 }
433
434 Grob *
435 Accidental_engraver::make_suggested_accidental (Stream_event *note,
436                                                 Grob *note_head,
437                                                 Engraver *trans)
438 {
439   (void) note;
440
441   Grob *a = trans->make_item ("AccidentalSuggestion", note_head->self_scm ());
442
443   Side_position_interface::add_support (a, note_head);
444   if (Grob *stem = unsmob_grob (a->get_object ("stem")))
445     Side_position_interface::add_support (a, stem);
446
447   a->set_parent (note_head, X_AXIS);
448   return a;
449 }
450
451 void
452 Accidental_engraver::finalize ()
453 {
454   last_keysig_ = SCM_EOL;
455 }
456
457 void
458 Accidental_engraver::stop_translation_timestep ()
459 {
460   for (vsize j = ties_.size (); j--;)
461     {
462       Grob *r = Tie::head (ties_[j], RIGHT);
463       for (vsize i = accidentals_.size (); i--;)
464         if (accidentals_[i].head_ == r)
465           {
466             if (Grob *g = accidentals_[i].accidental_)
467               {
468                 g->set_object ("tie", ties_[j]->self_scm ());
469                 accidentals_[i].tied_ = true;
470               }
471             ties_.erase (ties_.begin () + j);
472             break;
473           }
474     }
475
476   for (vsize i = accidentals_.size (); i--;)
477     {
478       int barnum = get_bar_number ();
479
480       Stream_event *note = accidentals_[i].melodic_;
481       Context *origin = accidentals_[i].origin_;
482
483       Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
484       if (!pitch)
485         continue;
486
487       int n = pitch->get_notename ();
488       int o = pitch->get_octave ();
489       Rational a = pitch->get_alteration ();
490       SCM key = scm_cons (scm_from_int (o), scm_from_int (n));
491
492       SCM localsig = SCM_EOL;
493       while (origin
494              && origin->where_defined (ly_symbol2scm ("localKeySignature"), &localsig))
495         {
496           bool change = false;
497           if (accidentals_[i].tied_)
498             {
499               /*
500                 Remember an alteration that is different both from
501                 that of the tied note and of the key signature.
502               */
503               localsig = ly_assoc_prepend_x (localsig, key, scm_cons (ly_symbol2scm ("tied"),
504                                                                       scm_from_int (barnum)));
505
506               change = true;
507             }
508           else
509             {
510               /*
511                 not really really correct if there are more than one
512                 noteheads with the same notename.
513               */
514               localsig = ly_assoc_prepend_x (localsig, key,
515                                            scm_cons (ly_rational2scm (a),
516                                                      scm_from_int (barnum)));
517               change = true;
518             }
519
520           if (change)
521             origin->set_property ("localKeySignature", localsig);
522
523           origin = origin->get_parent_context ();
524         }
525     }
526
527   if (accidental_placement_)
528     for (vsize i = 0; i < note_columns_.size (); i++)
529       Separation_item::add_conditional_item (note_columns_[i], accidental_placement_);
530
531   accidental_placement_ = 0;
532   accidentals_.clear ();
533   left_objects_.clear ();
534   right_objects_.clear ();
535 }
536
537 void
538 Accidental_engraver::acknowledge_rhythmic_head (Grob_info info)
539 {
540   Stream_event *note = info.event_cause ();
541   if (note
542       && (note->in_event_class ("note-event")
543           || note->in_event_class ("trill-span-event")))
544     {
545       /*
546         string harmonics usually don't have accidentals.
547       */
548       if (info.grob ()->get_property ("style") != ly_symbol2scm ("harmonic")
549           || to_boolean (get_property ("harmonicAccidentals")))
550         {
551           Accidental_entry entry;
552           entry.head_ = info.grob ();
553           entry.origin_engraver_ = dynamic_cast<Engraver *> (info.origin_translator ());
554           entry.origin_ = entry.origin_engraver_->context ();
555           entry.melodic_ = note;
556
557           accidentals_.push_back (entry);
558         }
559     }
560 }
561
562 void
563 Accidental_engraver::acknowledge_tie (Grob_info info)
564 {
565   ties_.push_back (dynamic_cast<Spanner *> (info.grob ()));
566 }
567
568 void
569 Accidental_engraver::acknowledge_note_column (Grob_info info)
570 {
571   note_columns_.push_back (info.grob ());
572 }
573
574 void
575 Accidental_engraver::acknowledge_arpeggio (Grob_info info)
576 {
577   left_objects_.push_back (info.grob ());
578 }
579
580 void
581 Accidental_engraver::acknowledge_finger (Grob_info info)
582 {
583   left_objects_.push_back (info.grob ());
584 }
585
586 void
587 Accidental_engraver::process_music ()
588 {
589   SCM sig = get_property ("keySignature");
590   if (last_keysig_ != sig)
591     update_local_key_signature (sig);
592 }
593
594 ADD_ACKNOWLEDGER (Accidental_engraver, arpeggio);
595 ADD_ACKNOWLEDGER (Accidental_engraver, finger);
596 ADD_ACKNOWLEDGER (Accidental_engraver, rhythmic_head);
597 ADD_ACKNOWLEDGER (Accidental_engraver, tie);
598 ADD_ACKNOWLEDGER (Accidental_engraver, note_column);
599
600 ADD_TRANSLATOR (Accidental_engraver,
601                 /* doc */
602                 "Make accidentals."
603                 "  Catch note heads, ties and notices key-change events."
604                 "  This engraver usually lives at Staff level, but"
605                 " reads the settings for Accidental at @code{Voice} level,"
606                 " so you can @code{\\override} them at @code{Voice}.",
607
608                 /* create */
609                 "Accidental "
610                 "AccidentalCautionary "
611                 "AccidentalSuggestion ",
612
613                 /* read */
614                 "autoAccidentals "
615                 "autoCautionaries "
616                 "internalBarNumber "
617                 "extraNatural "
618                 "harmonicAccidentals "
619                 "localKeySignature ",
620
621                 /* write */
622                 "localKeySignature "
623                 );