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