]> git.donarmstrong.com Git - lilypond.git/blob - lily/accidental-engraver.cc
3bd03fb69719c684e598189a7a8675bf47a51f6c
[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 "context.hh"
13 #include "engraver.hh"
14 #include "international.hh"
15 #include "pitch.hh"
16 #include "protected-scm.hh"
17 #include "rhythmic-head.hh"
18 #include "side-position-interface.hh"
19 #include "stream-event.hh"
20 #include "tie.hh"
21 #include "warn.hh"
22
23 #include "translator.icc"
24
25 class Accidental_entry
26 {
27 public:
28   bool done_;
29   Stream_event *melodic_;
30   Grob *accidental_;
31   Context *origin_;
32   Engraver *origin_engraver_;
33   Grob *head_;
34   bool tied_;
35
36   Accidental_entry ();
37 };
38
39 Accidental_entry::Accidental_entry ()
40 {
41   tied_ = false;
42   done_ = false;
43   melodic_ = 0;
44   accidental_ = 0;
45   origin_ = 0;
46   head_ = 0;
47 }
48
49 class Accidental_engraver : public Engraver
50 {
51   int get_bar_number ();
52   void update_local_key_signature ();
53   void create_accidental (Accidental_entry *entry, bool, bool);
54   Grob *make_standard_accidental (Stream_event *note, Grob *note_head, Engraver *trans);
55   Grob *make_suggested_accidental (Stream_event *note, Grob *note_head, Engraver *trans);
56
57 protected:
58   TRANSLATOR_DECLARATIONS (Accidental_engraver);
59   void process_music ();
60
61   void acknowledge_tie (Grob_info);
62   void acknowledge_arpeggio (Grob_info);
63   void acknowledge_rhythmic_head (Grob_info);
64   void acknowledge_finger (Grob_info);
65
66   void stop_translation_timestep ();
67   virtual void initialize ();
68   void process_acknowledged ();
69   virtual void finalize ();
70   virtual void derived_mark () const;
71
72 public:
73   SCM last_keysig_;     // ugh.
74
75   /*
76     Urgh. Since the accidentals depend on lots of variables, we have
77     to store all information before we can really create the
78     accidentals.
79   */
80   vector<Grob*> left_objects_;
81   vector<Grob*> right_objects_;
82
83   Grob *accidental_placement_;
84
85   vector<Accidental_entry> accidentals_;
86   vector<Spanner*> ties_;
87 };
88
89 /*
90   TODO:
91
92   ugh, it is not clear what properties are mutable and which
93   aren't. eg. localKeySignature is changed at runtime, which means
94   that references in grobs should always store ly_deep_copy ()s of
95   those.
96 */
97
98
99 Accidental_engraver::Accidental_engraver ()
100 {
101   accidental_placement_ = 0;
102   last_keysig_ = SCM_EOL;
103 }
104
105 void
106 Accidental_engraver::derived_mark () const
107 {
108   scm_gc_mark (last_keysig_);
109 }
110
111 void
112 Accidental_engraver::update_local_key_signature ()
113 {
114   last_keysig_ = get_property ("keySignature");
115   set_context_property_on_children (context (),
116                                     ly_symbol2scm ("localKeySignature"),
117                                     last_keysig_);
118
119   Context *trans = context ()->get_parent_context ();
120
121   /* Huh. Don't understand what this is good for. --hwn.  */
122
123   SCM val;
124   while (trans && trans->where_defined (ly_symbol2scm ("localKeySignature"), &val))
125     {
126       trans->set_property ("localKeySignature", ly_deep_copy (last_keysig_));
127       trans = trans->get_parent_context ();
128     }
129 }
130
131 void
132 Accidental_engraver::initialize ()
133 {
134   update_local_key_signature ();
135 }
136
137 /** Calculate the number of accidentals on basis of the current local key
138     sig (passed as argument)
139
140     * First check step+octave (taking into account barnumbers if necessary).
141
142     * Then check the global signature (only step).
143
144     Return number of accidentals (0, 1 or 2).  */
145
146 static bool
147 recent_enough (int bar_number, SCM alteration_def, SCM laziness)
148 {
149   if (scm_is_number (alteration_def)
150       || laziness == SCM_BOOL_T)
151     return true;
152
153   return (bar_number <= scm_to_int (scm_cdr (alteration_def)) + scm_to_int (laziness));
154 }
155
156 static int
157 extract_alteration (SCM alteration_def)
158 {
159   if (scm_is_number (alteration_def))
160     return scm_to_int (alteration_def);
161   else if (scm_is_pair (alteration_def))
162     return scm_to_int (scm_car (alteration_def));
163   else if (alteration_def == SCM_BOOL_F)
164     return 0;
165   else
166     assert (0);
167   return 0;
168 }
169
170 bool
171 is_tied (SCM alteration_def)
172 {
173   return (alteration_def == SCM_BOOL_T)
174     || (scm_is_pair (alteration_def) && scm_car (alteration_def) == SCM_BOOL_T);
175 }
176
177 static int
178 number_accidentals_from_sig (bool *different, SCM sig, Pitch *pitch,
179                              int bar_number, SCM laziness, bool ignore_octave)
180 {
181   int n = pitch->get_notename ();
182   int o = pitch->get_octave ();
183
184   SCM previous_alteration = SCM_BOOL_F;
185
186   SCM from_same_octave = ly_assoc_get (scm_cons (scm_from_int (o),
187                                                  scm_from_int (n)), sig, SCM_BOOL_F);
188   SCM from_key_signature = ly_assoc_get (scm_from_int (n), sig, SCM_BOOL_F);
189   SCM from_other_octaves = SCM_BOOL_F;
190   for (SCM s = sig; scm_is_pair (s); s = scm_cdr (s))
191     {
192       SCM entry = scm_car (s);
193       if (scm_is_pair (scm_car (entry))
194           && scm_cdar (entry) == scm_from_int (n))
195         from_other_octaves = scm_cdr (entry);
196     }
197
198   if (from_same_octave != SCM_BOOL_F
199       && recent_enough (bar_number, from_same_octave, laziness))
200     previous_alteration = from_same_octave;
201   else if (ignore_octave
202            && from_other_octaves != SCM_BOOL_F
203            && recent_enough (bar_number, from_other_octaves, laziness))
204     previous_alteration = from_other_octaves;
205   else if (from_key_signature != SCM_BOOL_F)
206     previous_alteration = from_key_signature;
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)
222                 || prev * alter < 0) && alter != 0)
223         num = 2;
224       *different = (alter != prev);
225     }
226   return num;
227 }
228
229 static int
230 number_accidentals (bool *different,
231                     Pitch *pitch, Context *origin,
232                     SCM accidentals, int bar_number)
233 {
234   int number = 0;
235
236   *different = false;
237   if (scm_is_pair (accidentals) && !scm_is_symbol (scm_car (accidentals)))
238     warning (_f ("accidental typesetting list must begin with context-name: %s",
239                  ly_scm2string (scm_car (accidentals)).c_str ()));
240
241   for (; scm_is_pair (accidentals) && origin;
242        accidentals = scm_cdr (accidentals))
243     {
244       // If pair then it is a new accidentals typesetting rule to be checked
245       SCM rule = scm_car (accidentals);
246       if (scm_is_pair (rule))
247         {
248           SCM type = scm_car (rule);
249           SCM laziness = scm_cdr (rule);
250           SCM localsig = origin->get_property ("localKeySignature");
251
252           bool same_octave_b
253             = scm_is_eq (ly_symbol2scm ("same-octave"), type);
254           bool any_octave_b
255             = scm_is_eq (ly_symbol2scm ("any-octave"), type);
256
257           if (same_octave_b || any_octave_b)
258             {
259               bool d = false;
260               int n = number_accidentals_from_sig
261                 (&d, localsig, pitch, bar_number, laziness, any_octave_b);
262               *different = *different || d;
263               number = max (number, n);
264             }
265           else
266             warning (_f ("ignoring unknown accidental: %s",
267                          ly_symbol2string (type).c_str ()));
268         }
269
270       /* if symbol then it is a context name.  Scan parent contexts to
271          find it. */
272       else if (scm_is_symbol (rule))
273         {
274           Context *dad = origin;
275           while (dad && !dad->is_alias (rule))
276             dad = dad->get_parent_context ();
277
278           if (dad)
279             origin = dad;
280         }
281       else
282         warning (_f ("pair or context-name expected for accidental rule, found %s",
283                      ly_scm2string (rule).c_str ()));
284     }
285
286   return number;
287 }
288
289 int
290 Accidental_engraver::get_bar_number ()
291 {
292   SCM barnum = get_property ("internalBarNumber");
293   SCM smp = get_property ("measurePosition");
294
295   int bn = robust_scm2int (barnum, 0);
296
297   Moment mp = robust_scm2moment (smp, Moment (0));
298   if (mp.main_part_ < Rational (0))
299     bn--;
300
301   return bn;
302 }
303
304 void
305 Accidental_engraver::process_acknowledged ()
306 {
307   if (accidentals_.size () && !accidentals_.back ().done_)
308     {
309       SCM accidentals = get_property ("autoAccidentals");
310       SCM cautionaries = get_property ("autoCautionaries");
311       int barnum = get_bar_number ();
312
313       for (vsize i = 0; i < accidentals_.size (); i++)
314         {
315           if (accidentals_[i].done_)
316             continue;
317           accidentals_[i].done_ = true;
318
319           Stream_event *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
337           bool cautionary = to_boolean (note->get_property ("cautionary"));
338           if (num_caut > num)
339             {
340               num = num_caut;
341               different = different_caut;
342               cautionary = true;
343             }
344
345           bool forced = to_boolean (note->get_property ("force-accidental"));
346           if (num == 0 && forced)
347             num = 1;
348
349           /* Cannot look for ties: it's not guaranteed that they reach
350              us before the notes. */
351           if (num
352               && !note->in_event_class ("trill-span-event"))
353             create_accidental (&accidentals_[i], num > 1, cautionary);
354
355
356           if (forced || cautionary)
357             accidentals_[i].accidental_->set_property ("forced", SCM_BOOL_T);
358         }
359     }
360 }
361
362 void
363 Accidental_engraver::create_accidental (Accidental_entry *entry,
364                                         bool restore_natural,
365                                         bool cautionary)
366 {
367   Stream_event *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 (Stream_event *note,
396                                                Grob *note_head,
397                                                Engraver *trans)
398 {
399
400   (void)note;
401   /*
402     We construct the accidentals at the originating Voice
403     level, so that we get the property settings for
404     Accidental from the respective Voice.
405   */
406   Grob *a = trans->make_item ("Accidental", note_head->self_scm ());
407
408   /*
409     We add the accidentals to the support of the arpeggio,
410     so it is put left of the accidentals.
411   */
412   for (vsize i = 0; i < left_objects_.size (); i++)
413     {
414       if (left_objects_[i]->get_property ("side-axis") == scm_from_int (X_AXIS))
415         Side_position_interface::add_support (left_objects_[i], a);
416     }
417
418   /*
419     Hmm. Junkme? 
420    */
421   for (vsize i = 0; i < right_objects_.size (); i++)
422     Side_position_interface::add_support (a, right_objects_[i]);
423
424   a->set_parent (note_head, Y_AXIS);
425
426   if (!accidental_placement_)
427     accidental_placement_ = make_item ("AccidentalPlacement",
428                                        a->self_scm ());
429   Accidental_placement::add_accidental (accidental_placement_, a);
430
431   note_head->set_object ("accidental-grob", a->self_scm ());
432
433   return a;
434 }
435
436 Grob *
437 Accidental_engraver::make_suggested_accidental (Stream_event *note,
438                                                 Grob *note_head,
439                                                 Engraver *trans)
440 {
441   (void) note;
442   Grob *a = trans->make_item ("AccidentalSuggestion", note_head->self_scm ());
443
444   Side_position_interface::add_support (a, note_head);
445   if (Grob *stem = unsmob_grob (a->get_object ("stem")))
446     Side_position_interface::add_support (a, stem);
447
448   a->set_parent (note_head, X_AXIS);
449   return a;
450 }
451
452 void
453 Accidental_engraver::finalize ()
454 {
455   last_keysig_ = SCM_EOL;
456 }
457
458 void
459 Accidental_engraver::stop_translation_timestep ()
460 {
461   for (vsize j = ties_.size (); j--;)
462     {
463       Grob *r = Tie::head (ties_[j], RIGHT);
464       for (vsize i = accidentals_.size (); i--;)
465         if (accidentals_[i].head_ == r)
466           {
467             if (Grob *g = accidentals_[i].accidental_)
468               {
469                 g->set_object ("tie", ties_[j]->self_scm ());
470                 accidentals_[i].tied_ = true;
471               }
472             ties_.erase (ties_.begin () + j);
473             break;
474           }
475     }
476
477   for (vsize i = accidentals_.size (); i--;)
478     {
479       int barnum = get_bar_number ();
480
481       Stream_event *note = accidentals_[i].melodic_;
482       Context *origin = accidentals_[i].origin_;
483
484       Pitch *pitch = unsmob_pitch (note->get_property ("pitch"));
485       if (!pitch)
486         continue;
487
488       int n = pitch->get_notename ();
489       int o = pitch->get_octave ();
490       int a = pitch->get_alteration ();
491       SCM key = scm_cons (scm_from_int (o), scm_from_int (n));
492
493       SCM localsig = SCM_EOL;
494       while (origin
495              && origin->where_defined (ly_symbol2scm ("localKeySignature"), &localsig))
496         {
497           bool change = false;
498           if (accidentals_[i].tied_)
499             {
500               /*
501                 Remember an alteration that is different both from
502                 that of the tied note and of the key signature.
503               */
504               localsig = ly_assoc_front_x
505                 (localsig, key, scm_cons (SCM_BOOL_T, scm_from_int (barnum)));
506
507               change = true;
508             }
509           else
510             {
511               /*
512                 not really really correct if there are more than one
513                 noteheads with the same notename.
514               */
515               localsig = ly_assoc_front_x (localsig, key,
516                                            scm_cons (scm_from_int (a),
517                                                      scm_from_int (barnum)));
518               change = true;
519             }
520
521           if (change)
522             origin->set_property ("localKeySignature", localsig);
523
524           origin = origin->get_parent_context ();
525         }
526     }
527
528   accidental_placement_ = 0;
529   accidentals_.clear ();
530   left_objects_.clear ();
531   right_objects_.clear ();
532 }
533
534 void
535 Accidental_engraver::acknowledge_rhythmic_head (Grob_info info)
536 {
537   Stream_event *note = info.event_cause ();
538   if (note
539       && (note->in_event_class ("note-event")
540           || note->in_event_class ("trill-span-event")))
541     {
542       /*
543         string harmonics usually don't have accidentals.
544       */
545       if (to_boolean (get_property ("harmonicAccidentals"))
546           || !ly_is_equal (info.grob ()->get_property ("style"),
547                            ly_symbol2scm ("harmonic")))
548         {
549           Accidental_entry entry;
550           entry.head_ = info.grob ();
551           entry.origin_engraver_ = dynamic_cast<Engraver *> (info.origin_translator ());
552           entry.origin_ = entry.origin_engraver_->context ();
553           entry.melodic_ = note;
554
555           accidentals_.push_back (entry);
556         }
557     }
558 }
559
560 void
561 Accidental_engraver::acknowledge_tie (Grob_info info)
562 {
563   ties_.push_back (dynamic_cast<Spanner *> (info.grob ()));
564 }
565
566 void
567 Accidental_engraver::acknowledge_arpeggio (Grob_info info)
568 {
569   left_objects_.push_back (info.grob ());
570 }
571
572 void
573 Accidental_engraver::acknowledge_finger (Grob_info info)
574 {
575   left_objects_.push_back (info.grob ());
576 }
577
578 void
579 Accidental_engraver::process_music ()
580 {
581   SCM sig = get_property ("keySignature");
582   /* Detect key sig changes.
583      Update all parents and children.  */
584   if (last_keysig_ != sig)
585     update_local_key_signature ();
586 }
587
588 ADD_ACKNOWLEDGER (Accidental_engraver, arpeggio);
589 ADD_ACKNOWLEDGER (Accidental_engraver, finger);
590 ADD_ACKNOWLEDGER (Accidental_engraver, rhythmic_head);
591 ADD_ACKNOWLEDGER (Accidental_engraver, tie);
592
593 ADD_TRANSLATOR (Accidental_engraver,
594                 
595                 "Make accidentals.  "
596                 "Catch note heads, ties and notices key-change events.  "
597                 "This engraver usually lives at Staff level, but "
598                 "reads the settings for Accidental at @code{Voice} level, "
599                 "so you can @code{\\override} them at @code{Voice}. ",
600                 "Accidental AccidentalSuggestion",
601
602                 "",
603
604                 "autoAccidentals "
605                 "autoCautionaries "
606                 "internalBarNumber "
607                 "extraNatural "
608                 "harmonicAccidentals "
609                 "localKeySignature",
610                 "localKeySignature");