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