]> git.donarmstrong.com Git - lilypond.git/blob - lily/accidental-engraver.cc
Nitpick run.
[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--2005 Han-Wen Nienhuys <hanwen@cs.uu.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 static void
98 set_property_on_children (Context *trans, char const *sym, SCM val)
99 {
100   trans->set_property (sym, ly_deep_copy (val));
101   for (SCM p = trans->children_contexts (); scm_is_pair (p); p = scm_cdr (p))
102     {
103       Context *trg = unsmob_context (scm_car (p));
104       set_property_on_children (trg, sym, ly_deep_copy (val));
105     }
106 }
107
108 Accidental_engraver::Accidental_engraver ()
109 {
110   accidental_placement_ = 0;
111   last_keysig_ = SCM_EOL;
112 }
113
114 void
115 Accidental_engraver::derived_mark () const
116 {
117   scm_gc_mark (last_keysig_);
118 }
119
120 void
121 Accidental_engraver::update_local_key_signature ()
122 {
123   last_keysig_ = get_property ("keySignature");
124   set_property_on_children (context (), "localKeySignature", last_keysig_);
125
126   Context *trans = context ()->get_parent_context ();
127
128   /* Huh. Don't understand what this is good for. --hwn.  */
129
130   SCM val;
131   while (trans && trans->where_defined (ly_symbol2scm ("localKeySignature"), &val))
132     {
133       trans->set_property ("localKeySignature", ly_deep_copy (last_keysig_));
134       trans = trans->get_parent_context ();
135     }
136 }
137
138 void
139 Accidental_engraver::initialize ()
140 {
141   update_local_key_signature ();
142 }
143
144 /** Calculate the number of accidentals on basis of the current local key
145     sig (passed as argument)
146
147     * First check step+octave (taking into account barnumbers if necessary).
148
149     * Then check the global signature (only step).
150
151     Return number of accidentals (0, 1 or 2).  */
152
153 static bool
154 recent_enough (int bar_number, SCM alteration_def, SCM laziness)
155 {
156   if (scm_is_number (alteration_def)
157       || laziness == SCM_BOOL_T)
158     return true;
159
160   return (bar_number <= scm_to_int (scm_cdr (alteration_def)) + scm_to_int (laziness));
161 }
162
163 static int
164 extract_alteration (SCM alteration_def)
165 {
166   if (scm_is_number (alteration_def))
167     return scm_to_int (alteration_def);
168   else if (scm_is_pair (alteration_def))
169     return scm_to_int (scm_car (alteration_def));
170   else if (alteration_def == SCM_BOOL_F)
171     return 0;
172   else
173     assert (0);
174   return 0;
175 }
176
177 bool
178 is_tied (SCM alteration_def)
179 {
180   return (alteration_def == SCM_BOOL_T)
181     || (scm_is_pair (alteration_def) && scm_car (alteration_def) == SCM_BOOL_T);
182 }
183
184 static int
185 number_accidentals_from_sig (bool *different, SCM sig, Pitch *pitch,
186                              int bar_number, SCM laziness, bool ignore_octave)
187 {
188   int n = pitch->get_notename ();
189   int o = pitch->get_octave ();
190
191   SCM previous_alteration = SCM_BOOL_F;
192
193   SCM from_same_octave = ly_assoc_get (scm_cons (scm_from_int (o),
194                                                  scm_from_int (n)), sig, SCM_BOOL_F);
195   SCM from_key_signature = ly_assoc_get (scm_from_int (n), sig, SCM_BOOL_F);
196   SCM from_other_octaves = SCM_BOOL_F;
197   for (SCM s = sig; scm_is_pair (s); s = scm_cdr (s))
198     {
199       SCM entry = scm_car (s);
200       if (scm_is_pair (scm_car (entry))
201           && scm_cdar (entry) == scm_from_int (n))
202         from_other_octaves = scm_cdr (entry);
203     }
204
205   if (from_same_octave != SCM_BOOL_F
206       && recent_enough (bar_number, from_same_octave, laziness))
207     previous_alteration = from_same_octave;
208   else if (ignore_octave
209            && from_other_octaves != SCM_BOOL_F
210            && recent_enough (bar_number, from_other_octaves, laziness))
211     previous_alteration = from_other_octaves;
212   else if (from_key_signature != SCM_BOOL_F)
213     previous_alteration = from_key_signature;
214
215   int num = 1;
216   if (is_tied (previous_alteration))
217     {
218       num = 1;
219       *different = true;
220     }
221   else
222     {
223       int prev = extract_alteration (previous_alteration);
224       int alter = pitch->get_alteration ();
225
226       if (alter == prev)
227         num = 0;
228       else if ((abs (alter) < abs (prev) || prev * alter < 0) && alter != 0)
229         num = 2;
230       *different = (alter != prev);
231     }
232   return num;
233 }
234
235 static int
236 number_accidentals (bool *different,
237                     Pitch *pitch, Context *origin,
238                     SCM accidentals, int bar_number)
239 {
240   int number = 0;
241
242   *different = false;
243   if (scm_is_pair (accidentals) && !scm_is_symbol (scm_car (accidentals)))
244     warning (_f ("accidental typesetting list must begin with context-name: %s",
245                  ly_scm2string (scm_car (accidentals)).to_str0 ()));
246
247   for (; scm_is_pair (accidentals) && origin;
248        accidentals = scm_cdr (accidentals))
249     {
250       // If pair then it is a new accidentals typesetting rule to be checked
251       SCM rule = scm_car (accidentals);
252       if (scm_is_pair (rule))
253         {
254           SCM type = scm_car (rule);
255           SCM laziness = scm_cdr (rule);
256           SCM localsig = origin->get_property ("localKeySignature");
257
258           bool same_octave_b
259             = scm_is_eq (ly_symbol2scm ("same-octave"), type);
260           bool any_octave_b
261             = scm_is_eq (ly_symbol2scm ("any-octave"), type);
262
263           if (same_octave_b || any_octave_b)
264             {
265               bool d = false;
266               int n = number_accidentals_from_sig
267                 (&d, localsig, pitch, bar_number, laziness, any_octave_b);
268               *different = *different || d;
269               number = max (number, n);
270             }
271           else
272             warning (_f ("ignoring unknown accidental: %s",
273                          ly_symbol2string (type).to_str0 ()));
274         }
275
276       /* if symbol then it is a context name.  Scan parent contexts to
277          find it. */
278       else if (scm_is_symbol (rule))
279         {
280           Context *dad = origin;
281           while (dad && !dad->is_alias (rule))
282             dad = dad->get_parent_context ();
283
284           if (dad)
285             origin = dad;
286         }
287       else
288         warning (_f ("pair or context-name expected for accidental rule, found %s",
289                      ly_scm2string (rule).to_str0 ()));
290     }
291
292   return number;
293 }
294
295 int
296 Accidental_engraver::get_bar_number ()
297 {
298   SCM barnum = get_property ("currentBarNumber");
299   SCM smp = get_property ("measurePosition");
300
301   int bn = robust_scm2int (barnum, 0);
302
303   Moment mp = robust_scm2moment (smp, Moment (0));
304   if (mp.main_part_ < Rational (0))
305     bn--;
306
307   return bn;
308 }
309
310 void
311 Accidental_engraver::process_acknowledged ()
312 {
313   if (accidentals_.size () && !accidentals_.top ().done_)
314     {
315       SCM accidentals = get_property ("autoAccidentals");
316       SCM cautionaries = get_property ("autoCautionaries");
317       int barnum = get_bar_number ();
318
319       for (int i = 0; i < accidentals_.size (); i++)
320         {
321           if (accidentals_[i].done_)
322             continue;
323           accidentals_[i].done_ = true;
324
325           Music *note = accidentals_[i].melodic_;
326           Context *origin = accidentals_[i].origin_;
327
328           Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
329           if (!pitch)
330             continue;
331
332           bool different = false;
333           bool different_caut = false;
334
335           int num = number_accidentals (&different,
336                                         pitch, origin,
337                                         accidentals, barnum);
338           int num_caut = number_accidentals (&different_caut,
339                                              pitch, origin,
340                                              cautionaries, barnum);
341
342           bool cautionary = to_boolean (note->get_property ("cautionary"));
343
344           if (num_caut > num)
345             {
346               num = num_caut;
347               different = different_caut;
348               cautionary = true;
349             }
350
351           if (num == 0 && to_boolean (note->get_property ("force-accidental")))
352             num = 1;
353
354           /* Cannot look for ties: it's not guaranteed that they reach
355              us before the notes. */
356           if (num)
357             create_accidental (&accidentals_[i], num > 1, cautionary);
358         }
359     }
360 }
361
362 void
363 Accidental_engraver::create_accidental (Accidental_entry *entry,
364                                         bool restore_natural,
365                                         bool cautionary)
366 {
367   Music *note = entry->melodic_;
368   Grob *support = entry->head_;
369   Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
370
371   bool as_suggestion = to_boolean (entry->origin_->get_property ("suggestAccidentals"));
372   Grob *a = 0;
373   if (as_suggestion)
374     a = make_suggested_accidental (note, support, entry->origin_engraver_);
375   else
376     a = make_standard_accidental (note, support, entry->origin_engraver_);
377
378   SCM accs = scm_cons (scm_from_int (pitch->get_alteration ()),
379                        SCM_EOL);
380   if (restore_natural)
381     {
382       if (to_boolean (get_property ("extraNatural")))
383         accs = scm_cons (scm_from_int (0), accs);
384     }
385
386   /* TODO: add cautionary option in accidental. */
387   if (cautionary)
388     a->set_property ("cautionary", SCM_BOOL_T);
389
390   a->set_property ("accidentals", accs);
391   entry->accidental_ = a;
392 }
393
394 Grob *
395 Accidental_engraver::make_standard_accidental (Music *note,
396                                                Grob *support,
397                                                Engraver *trans)
398 {
399
400   /*
401     We construct the accidentals at the originating Voice
402     level, so that we get the property settings for
403     Accidental from the respective Voice.
404   */
405   Grob *a
406     = make_grob_from_properties (trans,
407                                  ly_symbol2scm ("Accidental"),
408                                  note->self_scm (),
409                                  "Accidental");
410
411   /*
412     We add the accidentals to the support of the arpeggio,
413     so it is put left of the accidentals.
414   */
415   for (int i = 0; i < left_objects_.size (); i++)
416     Side_position_interface::add_support (left_objects_[i], a);
417   for (int i = 0; i < right_objects_.size (); i++)
418     Side_position_interface::add_support (a, right_objects_[i]);
419
420   a->set_parent (support, Y_AXIS);
421
422   if (!accidental_placement_)
423     accidental_placement_ = make_item ("AccidentalPlacement",
424                                        a->self_scm ());
425   Accidental_placement::add_accidental (accidental_placement_, a);
426
427   support->set_object ("accidental-grob", a->self_scm ());
428
429   return a;
430 }
431
432 Grob *
433 Accidental_engraver::make_suggested_accidental (Music *note,
434                                                 Grob *note_head, Engraver *trans)
435 {
436
437   Grob *a
438     = make_grob_from_properties (trans,
439                                  ly_symbol2scm ("AccidentalSuggestion"),
440                                  note->self_scm (),
441                                  "AccidentalSuggestion");
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 (int j = ties_.size (); j--;)
461     {
462       Grob *r = Tie::head (ties_[j], RIGHT);
463       for (int 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_.del (j);
472             break;
473           }
474     }
475
476   for (int i = accidentals_.size (); i--;)
477     {
478       int barnum = get_bar_number ();
479
480       Music *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       int 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_front_x
504                 (localsig, key, scm_cons (SCM_BOOL_T, 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_front_x (localsig, key,
515                                            scm_cons (scm_from_int (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   accidental_placement_ = 0;
528   accidentals_.clear ();
529   left_objects_.clear ();
530   right_objects_.clear ();
531 }
532
533 void
534 Accidental_engraver::acknowledge_rhythmic_head (Grob_info info)
535 {
536   Music *note = info.music_cause ();
537   if (note
538       && note->is_mus_type ("note-event"))
539     {
540       /*
541         String harmonics usually don't have accidentals.
542       */
543       if (to_boolean (get_property ("harmonicAccidentals"))
544           || !ly_is_equal (info.grob ()->get_property ("style"),
545                            ly_symbol2scm ("harmonic")))
546         {
547           Accidental_entry entry;
548           entry.head_ = info.grob ();
549           entry.origin_engraver_ = dynamic_cast<Engraver *> (info.origin_translator ());
550           entry.origin_ = entry.origin_engraver_->context ();
551           entry.melodic_ = note;
552
553           accidentals_.push (entry);
554         }
555     }
556 }
557
558 void
559 Accidental_engraver::acknowledge_tie (Grob_info info)
560 {
561   ties_.push (dynamic_cast<Spanner *> (info.grob ()));
562 }
563
564 void
565 Accidental_engraver::acknowledge_arpeggio (Grob_info info)
566 {
567   left_objects_.push (info.grob ());
568 }
569
570 void
571 Accidental_engraver::acknowledge_finger (Grob_info info)
572 {
573   left_objects_.push (info.grob ());
574 }
575
576 void
577 Accidental_engraver::process_music ()
578 {
579   SCM sig = get_property ("keySignature");
580   /* Detect key sig changes.
581      Update all parents and children.  */
582   if (last_keysig_ != sig)
583     update_local_key_signature ();
584 }
585
586 ADD_ACKNOWLEDGER (Accidental_engraver, arpeggio);
587 ADD_ACKNOWLEDGER (Accidental_engraver, finger);
588 ADD_ACKNOWLEDGER (Accidental_engraver, rhythmic_head);
589 ADD_ACKNOWLEDGER (Accidental_engraver, tie);
590
591 ADD_TRANSLATOR (Accidental_engraver,
592                 "Make accidentals.  "
593                 "Catch note heads, ties and notices key-change events.  "
594                 "This engraver usually lives at Staff level, but "
595                 "reads the settings for Accidental at @code{Voice} level, "
596                 "so you can @code{\\override} them at @code{Voice}. ",
597                 "Accidental AccidentalSuggestion",
598
599                 "",
600
601                 "autoAccidentals "
602                 "autoCautionaries "
603                 "extraNatural "
604                 "harmonicAccidentals "
605                 "localKeySignature",
606                 "localKeySignature");