]> git.donarmstrong.com Git - lilypond.git/blob - lily/accidental-engraver.cc
(recent_enough): interpret laziness
[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--2004 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 "event.hh"
15 #include "item.hh"
16 #include "protected-scm.hh"
17 #include "rhythmic-head.hh"
18 #include "side-position-interface.hh"
19 #include "spanner.hh"
20 #include "tie.hh"
21 #include "warn.hh"
22
23
24 class Accidental_entry
25 {
26 public:
27   bool done_;
28   Music *melodic_;
29   Grob *accidental_;
30   Context *origin_;
31   Engraver *origin_trans_;
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 public:
51   int get_bar_number ();
52   void update_local_key_signature ();
53
54 protected:
55   TRANSLATOR_DECLARATIONS (Accidental_engraver);
56   virtual void process_music ();
57   virtual void acknowledge_grob (Grob_info);
58   virtual void stop_translation_timestep ();
59   virtual void initialize ();
60   virtual void process_acknowledged_grobs ();
61   virtual void finalize ();
62
63   virtual void derived_mark () const;
64 public:
65   SCM last_keysig_;     // ugh.
66   
67   /* Urgh. Since the accidentals depend on lots of variables, we have
68     to store all information before we can really create the
69     accidentals.  */
70   Link_array<Grob> left_objects_;
71   Link_array<Grob> right_objects_;
72
73   Grob *accidental_placement_;
74
75   Array<Accidental_entry> accidentals_;
76   Link_array<Spanner> ties_;
77 };
78
79
80 /*
81   TODO:
82
83   ugh, it is not clear what properties are mutable and which
84   aren't. eg. localKeySignature is changed at runtime, which means
85   that references in grobs should always store ly_deep_copy ()s of
86   those.
87  */
88
89 static void
90 set_property_on_children (Context *trans, char const *sym, SCM val)
91 {
92   trans->set_property (sym, ly_deep_copy (val));
93   for (SCM p = trans->children_contexts (); ly_c_pair_p (p); p = ly_cdr (p))
94     {
95       Context *trg = unsmob_context (ly_car (p));
96       set_property_on_children (trg, sym, ly_deep_copy (val));
97     }
98 }
99
100 Accidental_engraver::Accidental_engraver ()
101 {
102   accidental_placement_ = 0;
103   last_keysig_ = SCM_EOL;
104 }
105
106 void
107 Accidental_engraver::derived_mark () const
108 {
109   scm_gc_mark (last_keysig_);
110 }
111
112 void
113 Accidental_engraver::update_local_key_signature ()
114 {
115   last_keysig_ = get_property ("keySignature");
116   set_property_on_children (context (), "localKeySignature", last_keysig_);
117
118   Context *trans = context ()->get_parent_context ();
119
120   /* Huh. Don't understand what this is good for. --hwn.  */
121   while (trans && trans->where_defined (ly_symbol2scm ("localKeySignature")))
122     {
123       trans->set_property ("localKeySignature", ly_deep_copy (last_keysig_));
124       trans = trans->get_parent_context ();
125     }
126 }
127
128 void
129 Accidental_engraver::initialize ()
130 {
131   update_local_key_signature (); 
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 (ly_cdr (alteration_def)) + scm_to_int (laziness));
152 }
153
154 static int
155 extract_alteration (SCM alteration_def)
156 {
157   if (scm_is_number (alteration_def))
158     return scm_to_int (alteration_def);
159   else if (ly_c_pair_p (alteration_def))
160     return scm_to_int (ly_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 static int
169 number_accidentals_from_sig (bool *different, SCM sig, Pitch *pitch,
170                              int bar_number, SCM laziness, bool ignore_octave)
171 {
172   int n = pitch->get_notename ();
173   int o = pitch->get_octave ();
174
175   SCM previous_alteration = SCM_BOOL_F;
176
177
178   SCM from_same_octave = ly_assoc_get (scm_cons (scm_int2num (o),
179                                                      scm_int2num (n)), sig, SCM_BOOL_F);
180   SCM from_key_signature = ly_assoc_get (scm_int2num (n), sig, SCM_BOOL_F);
181   SCM from_other_octaves = SCM_BOOL_F;
182   for (SCM s = sig ; ly_c_pair_p (s); s = ly_cdr (s))
183     {
184       SCM entry = ly_car (s);
185       if (ly_c_pair_p (ly_car (entry))
186           && ly_cdar (entry) == scm_int2num (n))
187         from_other_octaves = ly_cdr (entry); 
188     }
189   
190
191   if (from_same_octave != SCM_BOOL_F
192       && recent_enough (bar_number, from_same_octave, laziness))
193     {
194       previous_alteration = from_same_octave;
195     }
196   else if (ignore_octave
197            && from_other_octaves != SCM_BOOL_F
198            && recent_enough (bar_number, from_other_octaves, laziness))
199     {
200       previous_alteration = from_other_octaves;
201     }
202   else if (from_key_signature != SCM_BOOL_F)
203     {
204       previous_alteration = from_key_signature;
205     }
206   
207   /* UGH. prev_acc can be #t in case of ties. What is this for?  */
208
209   int prev = extract_alteration (previous_alteration);
210   int alter = pitch->get_alteration ();
211   int num = 1;
212   if (alter == prev)
213     num = 0;
214   else if ((abs (alter) < abs (prev) || prev*alter < 0) && alter != 0)
215     num = 2;
216
217   *different = (alter != prev);
218   return num;
219 }
220
221 static int
222 number_accidentals (bool *different,
223                     Pitch *pitch, Context *origin,
224                     SCM accidentals, int bar_number)
225 {
226   int number = 0;
227
228   *different = false;
229   if (ly_c_pair_p (accidentals) && !scm_is_symbol (ly_car (accidentals)))
230     warning (_f ("Accidental typesetting list must begin with context-name: %s", 
231                  ly_scm2string (ly_car (accidentals)).to_str0 ()));
232   
233   for (; ly_c_pair_p (accidentals) && origin;
234        accidentals = ly_cdr (accidentals))
235     {
236       // If pair then it is a new accidentals typesetting rule to be checked
237       SCM rule = ly_car (accidentals);
238       if (ly_c_pair_p (rule))
239         {
240           SCM type = ly_car (rule);
241           SCM laziness = ly_cdr (rule);
242           SCM localsig = origin->get_property ("localKeySignature");
243           
244           bool same_octave_b = 
245             scm_is_eq (ly_symbol2scm ("same-octave"), type);
246           bool any_octave_b = 
247             scm_is_eq (ly_symbol2scm ("any-octave"), type);
248
249           if (same_octave_b || any_octave_b)
250             {
251               bool d = false;
252               int n = number_accidentals_from_sig
253                 (&d, localsig, pitch, bar_number, laziness, any_octave_b);
254               *different = *different || d;
255               number = max (number, n);     
256             }
257           else
258             warning (_f ("ignoring unknown accidental: %s", 
259                          ly_symbol2string (type).to_str0 ()));
260         }
261       
262
263       /*
264         if symbol then it is a context name. Scan parent contexts to find it.
265       */
266       else if (scm_is_symbol (rule))
267         {
268           Context *dad = origin;
269           while (dad && !dad->is_alias (rule))
270             dad = dad->get_parent_context ();
271       
272           if (dad)
273             origin = dad;
274         }
275       else warning (_f ("Accidental rule must be pair or context-name; Found %s", 
276                         ly_scm2string (rule).to_str0 ()));
277     }
278
279   return number;
280 }
281
282 int
283 Accidental_engraver::get_bar_number ()
284 {
285   SCM barnum = get_property ("currentBarNumber");
286   SCM smp = get_property ("measurePosition");
287
288   int bn = robust_scm2int (barnum, 0);
289   
290   Moment mp = (unsmob_moment (smp)) ? *unsmob_moment (smp) : Moment (0);
291   if (mp.main_part_ < Rational (0))
292     bn--;
293   
294   return bn;
295 }
296
297 void
298 Accidental_engraver::process_acknowledged_grobs ()
299 {
300   if (accidentals_.size () && !accidentals_.top ().done_)
301     {
302       SCM accidentals =  get_property ("autoAccidentals");
303       SCM cautionaries =  get_property ("autoCautionaries");
304       int barnum = get_bar_number ();
305       
306       bool extra_natural_b = get_property ("extraNatural") == SCM_BOOL_T;
307       for (int i = 0; i < accidentals_.size (); i++) 
308         {
309           if (accidentals_[i].done_ )
310             continue;
311           accidentals_[i].done_  = true;
312           Grob *support = accidentals_[i].head_;
313           Music *note = accidentals_[i].melodic_;
314           Context *origin = accidentals_[i].origin_;
315
316           Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
317           if (!pitch)
318             continue;
319
320           bool different = false;
321           bool different_caut = false;
322           
323           int num = number_accidentals (&different,
324                                         pitch, origin,
325                                         accidentals, barnum);
326           int num_caut = number_accidentals (&different_caut,
327                                              pitch, origin,
328                                              cautionaries, barnum);
329
330           bool cautionary = to_boolean (note->get_property ("cautionary"));
331           
332           if (num_caut > num)
333             {
334               num = num_caut;
335               different = different_caut;
336               cautionary = true;
337             }
338
339           if (num == 0 && to_boolean (note->get_property ("force-accidental")))
340             num = 1;
341           
342
343           /*
344             Can not look for ties: it's not guaranteed that they reach
345             us before the notes
346            */
347         
348           if (num)
349             {
350               /*
351                 We construct the accidentals at the originating Voice
352                 level, so that we get the property settings for
353                 Accidental from the respective Voice.
354                */
355               Grob *a
356                 = make_item_from_properties (accidentals_[i].origin_trans_,
357                                              ly_symbol2scm ("Accidental"),
358                                              note->self_scm ());
359               a->set_parent (support, Y_AXIS);
360
361               if (!accidental_placement_)
362                 accidental_placement_ = make_item ("AccidentalPlacement",
363                                                    a->self_scm ());
364               Accidental_placement::add_accidental (accidental_placement_, a);
365               SCM accs = scm_cons (scm_int2num (pitch->get_alteration ()),
366                                    SCM_EOL);
367               if (num == 2 && extra_natural_b)
368                 accs = scm_cons (scm_int2num (0), accs);
369
370               /* TODO: add cautionary option in accidental. */
371
372               if (cautionary)
373                 a->set_property ("cautionary", SCM_BOOL_T);
374               
375               support->set_property ("accidental-grob", a->self_scm ());
376
377               a->set_property ("accidentals", accs);
378               accidentals_[i].accidental_ = a;
379
380               /*
381                 We add the accidentals to the support of the arpeggio,
382                 so it is put left of the accidentals.
383               */
384               for (int i = 0;  i < left_objects_.size ();  i++)
385                 Side_position_interface::add_support (left_objects_[i], a);
386               for (int i = 0;  i < right_objects_.size ();  i++)
387                 Side_position_interface::add_support (a, right_objects_[i]);
388             }
389         }
390     }
391 }
392
393 void
394 Accidental_engraver::finalize ()
395 {
396   last_keysig_ = SCM_EOL;
397 }
398
399 void
400 Accidental_engraver::stop_translation_timestep ()
401 {
402   for (int j = ties_.size (); j--;)
403     {
404       Grob *r = Tie::head (ties_[j], RIGHT);
405       for (int i = accidentals_.size ();  i--;)
406         if (accidentals_[i].head_ == r)
407           {
408             if (Grob *g = accidentals_[i].accidental_)
409               {
410                 g->set_property ("tie", ties_[j]->self_scm ());
411                 accidentals_[i].tied_ = true;
412               }
413             ties_.del (j);
414             break;
415           }
416     }
417
418   for (int i = accidentals_.size (); i--;) 
419     {
420       int barnum = get_bar_number ();
421
422       Music *note = accidentals_[i].melodic_;
423       Context * origin = accidentals_[i].origin_;
424
425       Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
426       if (!pitch)
427         continue;
428
429       int n = pitch->get_notename ();
430       int o = pitch->get_octave ();
431       int a = pitch->get_alteration ();
432       SCM key = scm_cons (scm_int2num (o), scm_int2num (n));
433
434       while (origin
435              && origin->where_defined (ly_symbol2scm ("localKeySignature")))
436         {
437           /*
438             huh? we set props all the way to the top? 
439           */
440           SCM localsig = origin->get_property ("localKeySignature");
441           bool change = false;
442           if (accidentals_[i].tied_)
443             {
444               /*
445                 Remember an alteration that is different both from
446                 that of the tied note and of the key signature.
447               */
448               localsig = ly_assoc_front_x
449                 (localsig, key, scm_cons (SCM_BOOL_T, scm_int2num (barnum)));
450
451               change = true;
452             }
453           else
454             {
455               /*
456                 not really really correct if there are more than one
457                 noteheads with the same notename.
458               */
459               localsig = ly_assoc_front_x (localsig, key,
460                                            scm_cons (scm_int2num (a),
461                                                      scm_int2num (barnum)));
462               change = true;
463             }
464
465           if (change)
466             origin->set_property ("localKeySignature", localsig);
467
468           origin = origin->get_parent_context ();
469         }
470     }
471
472   accidental_placement_ = 0;
473   accidentals_.clear ();
474   left_objects_.clear ();
475   right_objects_.clear ();
476 }
477
478 void
479 Accidental_engraver::acknowledge_grob (Grob_info info)
480 {
481   Music *note = info.music_cause ();
482
483   if (note
484       && note->is_mus_type ("note-event")
485       && Rhythmic_head::has_interface (info.grob_))
486     {
487       if (to_boolean ( get_property ("harmonicAccidentals"))
488           || !ly_c_equal_p (info.grob_->get_property ("style"),
489                           ly_symbol2scm ("harmonic")))
490         {
491           
492           Accidental_entry entry ;
493           entry.head_ = info.grob_;
494           entry.origin_trans_ = dynamic_cast<Engraver*> (info.origin_trans_);
495           entry.origin_ = info.origin_trans_->context ();
496           entry.melodic_ = note;
497
498           accidentals_.push (entry);
499         }
500     }
501   else if (Tie::has_interface (info.grob_))
502     ties_.push (dynamic_cast<Spanner*> (info.grob_));
503   else if (Arpeggio::has_interface (info.grob_))
504     left_objects_.push (info.grob_); 
505   else if (info.grob_
506            ->internal_has_interface (ly_symbol2scm ("finger-interface")))
507     left_objects_.push (info.grob_); 
508 }
509
510 void
511 Accidental_engraver::process_music ()
512 {
513   SCM sig = get_property ("keySignature");
514   /* Detect key sig changes.
515      Update all parents and children.  */
516   if (last_keysig_ != sig)
517     update_local_key_signature ();
518 }
519
520 ENTER_DESCRIPTION (Accidental_engraver,
521                    "Make accidentals.  "
522                    "Catch note heads, ties and notices key-change events.  "
523                    "This engraver usually lives at Staff level, but "
524                    "reads the settings for Accidental at @code{Voice} level, " 
525                    "so you can @code{\\override} them at @code{Voice}. "
526                    ,
527                    "Accidental"
528                    ,
529                    ""
530                    ,
531                    "arpeggio-interface "
532                    "finger-interface "
533                    "rhythmic-head-interface "
534                    "tie-interface "
535                    ,
536                    "autoAccidentals "
537                    "autoCautionaries "
538                    "extraNatural "
539                    "harmonicAccidentals "
540                    "localKeySignature"
541                    ,
542                    "localKeySignature"
543                    );