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