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