]> git.donarmstrong.com Git - lilypond.git/blob - lily/accidental-engraver.cc
use rational numbers for alteration field of Pitch.
[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   
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   /* Reset parent contexts so that e.g. piano-accidentals won't remember old
124      cross-staff accidentals after key-sig-changes */
125
126   SCM val;
127   while (trans && trans->where_defined (ly_symbol2scm ("localKeySignature"), &val)==trans)
128     {
129       trans->set_property ("localKeySignature", ly_deep_copy (last_keysig_));
130       trans = trans->get_parent_context ();
131     }
132 }
133
134
135 /** Calculate the number of accidentals on basis of the current local key
136     sig (passed as argument)
137
138     * First check step+octave (taking into account barnumbers if necessary).
139
140     * Then check the global signature (only step).
141
142     Return number of accidentals (0, 1 or 2).  */
143
144 static bool
145 recent_enough (int bar_number, SCM alteration_def, SCM laziness)
146 {
147   if (scm_is_number (alteration_def)
148       || laziness == SCM_BOOL_T)
149     return true;
150
151   return (bar_number <= scm_to_int (scm_cdr (alteration_def)) + scm_to_int (laziness));
152 }
153
154 static Rational
155 extract_alteration (SCM alteration_def)
156 {
157   if (scm_is_number (alteration_def))
158     return ly_scm2rational (alteration_def);
159   else if (scm_is_pair (alteration_def))
160     return ly_scm2rational (scm_car (alteration_def));
161   else if (alteration_def == SCM_BOOL_F)
162     return 0;
163   else
164     assert (0);
165   return 0;
166 }
167
168 bool
169 is_tied (SCM alteration_def)
170 {
171   return (alteration_def == SCM_BOOL_T)
172     || (scm_is_pair (alteration_def) && scm_car (alteration_def) == SCM_BOOL_T);
173 }
174
175 static int
176 number_accidentals_from_sig (bool *different, SCM sig, Pitch *pitch,
177                              int bar_number, SCM laziness, bool ignore_octave)
178 {
179   int n = pitch->get_notename ();
180   int o = pitch->get_octave ();
181
182   SCM previous_alteration = SCM_BOOL_F;
183
184   SCM from_same_octave = ly_assoc_get (scm_cons (scm_from_int (o),
185                                                  scm_from_int (n)), sig, SCM_BOOL_F);
186   SCM from_key_signature = ly_assoc_get (scm_from_int (n), sig, SCM_BOOL_F);
187   SCM from_other_octaves = SCM_BOOL_F;
188   for (SCM s = sig; scm_is_pair (s); s = scm_cdr (s))
189     {
190       SCM entry = scm_car (s);
191       if (scm_is_pair (scm_car (entry))
192           && scm_cdar (entry) == scm_from_int (n))
193         {
194           from_other_octaves = scm_cdr (entry);
195           break;
196         }
197     }
198
199   if (!ignore_octave
200       && from_same_octave != SCM_BOOL_F
201       && recent_enough (bar_number, from_same_octave, laziness))
202     previous_alteration = from_same_octave;
203   else if (ignore_octave
204            && from_other_octaves != SCM_BOOL_F
205            && recent_enough (bar_number, from_other_octaves, laziness))
206     previous_alteration = from_other_octaves;
207   else if (from_key_signature != SCM_BOOL_F)
208     previous_alteration = from_key_signature;
209
210   int num = 1;
211   if (is_tied (previous_alteration))
212     {
213       num = 1;
214       *different = true;
215     }
216   else
217     {
218       Rational prev = extract_alteration (previous_alteration);
219       Rational alter = pitch->get_alteration ();
220
221       if (alter == prev)
222         num = 0;
223       else if ((alter.abs () < prev.abs ()
224                 || (prev * alter).sign () < 0) && alter.sign ())
225         num = 2;
226       *different = (alter != prev);
227     }
228   return num;
229 }
230
231 static int
232 number_accidentals (bool *different,
233                     Pitch *pitch, Context *origin,
234                     SCM accidentals, int bar_number)
235 {
236   int number = 0;
237
238   *different = false;
239   if (scm_is_pair (accidentals) && !scm_is_symbol (scm_car (accidentals)))
240     warning (_f ("accidental typesetting list must begin with context-name: %s",
241                  ly_scm2string (scm_car (accidentals)).c_str ()));
242
243   for (; scm_is_pair (accidentals) && origin;
244        accidentals = scm_cdr (accidentals))
245     {
246       // If pair then it is a new accidentals typesetting rule to be checked
247       SCM rule = scm_car (accidentals);
248       if (scm_is_pair (rule))
249         {
250           SCM type = scm_car (rule);
251           SCM laziness = scm_cdr (rule);
252           SCM localsig = origin->get_property ("localKeySignature");
253
254           bool same_octave_b
255             = scm_is_eq (ly_symbol2scm ("same-octave"), type);
256           bool any_octave_b
257             = scm_is_eq (ly_symbol2scm ("any-octave"), type);
258
259           if (same_octave_b || any_octave_b)
260             {
261               bool d = false;
262               int n = number_accidentals_from_sig
263                 (&d, localsig, pitch, bar_number, laziness, any_octave_b);
264               *different = *different || d;
265               number = max (number, n);
266             }
267           else
268             warning (_f ("ignoring unknown accidental: %s",
269                          ly_symbol2string (type).c_str ()));
270         }
271
272       /* if symbol then it is a context name.  Scan parent contexts to
273          find it. */
274       else if (scm_is_symbol (rule))
275         {
276           Context *dad = origin;
277           while (dad && !dad->is_alias (rule))
278             dad = dad->get_parent_context ();
279
280           if (dad)
281             origin = dad;
282         }
283       else
284         warning (_f ("pair or context-name expected for accidental rule, found %s",
285                      ly_scm2string (rule).c_str ()));
286     }
287
288   return number;
289 }
290
291 int
292 Accidental_engraver::get_bar_number ()
293 {
294   SCM barnum = get_property ("internalBarNumber");
295   SCM smp = get_property ("measurePosition");
296
297   int bn = robust_scm2int (barnum, 0);
298
299   Moment mp = robust_scm2moment (smp, Moment (0));
300   if (mp.main_part_ < Rational (0))
301     bn--;
302
303   return bn;
304 }
305
306 void
307 Accidental_engraver::process_acknowledged ()
308 {
309   if (accidentals_.size () && !accidentals_.back ().done_)
310     {
311       SCM accidentals = get_property ("autoAccidentals");
312       SCM cautionaries = get_property ("autoCautionaries");
313       int barnum = get_bar_number ();
314
315       for (vsize i = 0; i < accidentals_.size (); i++)
316         {
317           if (accidentals_[i].done_)
318             continue;
319           accidentals_[i].done_ = true;
320
321           Stream_event *note = accidentals_[i].melodic_;
322           Context *origin = accidentals_[i].origin_;
323
324           Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
325           if (!pitch)
326             continue;
327
328           bool different = false;
329           bool different_caut = false;
330
331           int num = number_accidentals (&different,
332                                         pitch, origin,
333                                         accidentals, barnum);
334           int num_caut = number_accidentals (&different_caut,
335                                              pitch, origin,
336                                              cautionaries, barnum);
337
338
339           bool cautionary = to_boolean (note->get_property ("cautionary"));
340           if (num_caut > num)
341             {
342               num = num_caut;
343               different = different_caut;
344               cautionary = true;
345             }
346
347           bool forced = to_boolean (note->get_property ("force-accidental"));
348           if (num == 0 && forced)
349             num = 1;
350
351           /* Cannot look for ties: it's not guaranteed that they reach
352              us before the notes. */
353           if (num
354               && !note->in_event_class ("trill-span-event"))
355             create_accidental (&accidentals_[i], num > 1, cautionary);
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 () * Rational (4)),
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   (void)note;
401
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
444   Grob *a = trans->make_item ("AccidentalSuggestion", note_head->self_scm ());
445
446   Side_position_interface::add_support (a, note_head);
447   if (Grob *stem = unsmob_grob (a->get_object ("stem")))
448     Side_position_interface::add_support (a, stem);
449
450   a->set_parent (note_head, X_AXIS);
451   return a;
452 }
453
454 void
455 Accidental_engraver::finalize ()
456 {
457   last_keysig_ = SCM_EOL;
458 }
459
460 void
461 Accidental_engraver::stop_translation_timestep ()
462 {
463   for (vsize j = ties_.size (); j--;)
464     {
465       Grob *r = Tie::head (ties_[j], RIGHT);
466       for (vsize i = accidentals_.size (); i--;)
467         if (accidentals_[i].head_ == r)
468           {
469             if (Grob *g = accidentals_[i].accidental_)
470               {
471                 g->set_object ("tie", ties_[j]->self_scm ());
472                 accidentals_[i].tied_ = true;
473               }
474             ties_.erase (ties_.begin () + j);
475             break;
476           }
477     }
478
479   for (vsize i = accidentals_.size (); i--;)
480     {
481       int barnum = get_bar_number ();
482
483       Stream_event *note = accidentals_[i].melodic_;
484       Context *origin = accidentals_[i].origin_;
485
486       Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
487       if (!pitch)
488         continue;
489
490       int n = pitch->get_notename ();
491       int o = pitch->get_octave ();
492       Rational a = pitch->get_alteration ();
493       SCM key = scm_cons (scm_from_int (o), scm_from_int (n));
494
495       SCM localsig = SCM_EOL;
496       while (origin
497              && origin->where_defined (ly_symbol2scm ("localKeySignature"), &localsig))
498         {
499           bool change = false;
500           if (accidentals_[i].tied_)
501             {
502               /*
503                 Remember an alteration that is different both from
504                 that of the tied note and of the key signature.
505               */
506               localsig = ly_assoc_front_x
507                 (localsig, key, scm_cons (SCM_BOOL_T, scm_from_int (barnum)));
508
509               change = true;
510             }
511           else
512             {
513               /*
514                 not really really correct if there are more than one
515                 noteheads with the same notename.
516               */
517               localsig = ly_assoc_front_x (localsig, key,
518                                            scm_cons (ly_rational2scm (a),
519                                                      scm_from_int (barnum)));
520               change = true;
521             }
522
523           if (change)
524             origin->set_property ("localKeySignature", localsig);
525
526           origin = origin->get_parent_context ();
527         }
528     }
529
530   accidental_placement_ = 0;
531   accidentals_.clear ();
532   left_objects_.clear ();
533   right_objects_.clear ();
534 }
535
536 void
537 Accidental_engraver::acknowledge_rhythmic_head (Grob_info info)
538 {
539   Stream_event *note = info.event_cause ();
540   if (note
541       && (note->in_event_class ("note-event")
542           || note->in_event_class ("trill-span-event")))
543     {
544       /*
545         string harmonics usually don't have accidentals.
546       */
547       if (to_boolean (get_property ("harmonicAccidentals"))
548           || !ly_is_equal (info.grob ()->get_property ("style"),
549                            ly_symbol2scm ("harmonic")))
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_arpeggio (Grob_info info)
570 {
571   left_objects_.push_back (info.grob ());
572 }
573
574 void
575 Accidental_engraver::acknowledge_finger (Grob_info info)
576 {
577   left_objects_.push_back (info.grob ());
578 }
579
580 void
581 Accidental_engraver::process_music ()
582 {
583   SCM sig = get_property ("keySignature");
584   /* Detect key sig changes.
585      Update all parents and children.  */
586   if (last_keysig_ != sig)
587     update_local_key_signature ();
588 }
589
590 ADD_ACKNOWLEDGER (Accidental_engraver, arpeggio);
591 ADD_ACKNOWLEDGER (Accidental_engraver, finger);
592 ADD_ACKNOWLEDGER (Accidental_engraver, rhythmic_head);
593 ADD_ACKNOWLEDGER (Accidental_engraver, tie);
594
595 ADD_TRANSLATOR (Accidental_engraver,
596                 
597                 "Make accidentals.  "
598                 "Catch note heads, ties and notices key-change events.  "
599                 "This engraver usually lives at Staff level, but "
600                 "reads the settings for Accidental at @code{Voice} level, "
601                 "so you can @code{\\override} them at @code{Voice}. ",
602                 "Accidental AccidentalSuggestion",
603
604                 "autoAccidentals "
605                 "autoCautionaries "
606                 "internalBarNumber "
607                 "extraNatural "
608                 "harmonicAccidentals "
609                 "localKeySignature ",
610                 "localKeySignature "
611                 );