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