1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3 
4   Copyright (C) 1997--2020 Han-Wen Nienhuys <hanwen@xs4all.nl>
5 
6   LilyPond is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10 
11   LilyPond is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15 
16   You should have received a copy of the GNU General Public License
17   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
18 */
19 
20 #include "paper-column.hh"
21 
22 #include "axis-group-interface.hh"
23 #include "bar-line.hh"
24 #include "break-align-interface.hh"
25 #include "font-interface.hh"
26 #include "grob-array.hh"
27 #include "lookup.hh"
28 #include "moment.hh"
29 #include "output-def.hh"
30 #include "paper-score.hh"
31 #include "pointer-group-interface.hh"
32 #include "rhythmic-head.hh"
33 #include "separation-item.hh"
34 #include "skyline-pair.hh"
35 #include "spaceable-grob.hh"
36 #include "spring.hh"
37 #include "string-convert.hh"
38 #include "system.hh"
39 #include "text-interface.hh"
40 #include "warn.hh"
41 
42 using std::string;
43 using std::vector;
44 
45 bool
internal_set_as_bound_of_spanner(Spanner * s,Direction)46 Paper_column::internal_set_as_bound_of_spanner (Spanner *s, Direction)
47 {
48   bool ok = s->accepts_as_bound_paper_column (this);
49   if (ok)
50     {
51       // Signal that this column needs to be kept alive. They need to be kept
52       // alive to have meaningful position and linebreaking.  [maybe we should
53       // try keeping all columns alive?, and perhaps inherit position from
54       // their (non-)musical brother]
55       Pointer_group_interface::add_grob (this, ly_symbol2scm ("bounded-by-me"), s);
56     }
57   return ok;
58 }
59 
60 void
set_rank(int rank)61 Paper_column::set_rank (int rank)
62 {
63   rank_ = rank;
64 }
65 
66 System *
get_system() const67 Paper_column::get_system () const
68 {
69   return system_;
70 }
71 
72 void
set_system(System * s)73 Paper_column::set_system (System *s)
74 {
75   system_ = s;
76 }
77 
78 Paper_column *
get_column() const79 Paper_column::get_column () const
80 {
81   return (Paper_column *) (this);
82 }
83 
Paper_column(SCM l)84 Paper_column::Paper_column (SCM l)
85   : Item (l)
86 {
87   system_ = 0;
88   rank_ = -1;
89 }
90 
Paper_column(Paper_column const & src)91 Paper_column::Paper_column (Paper_column const &src)
92   : Item (src)
93 {
94   system_ = 0;
95   rank_ = src.rank_;
96 }
97 
98 Moment
when_mom(Grob * me)99 Paper_column::when_mom (Grob *me)
100 {
101   SCM m = get_property (me, "when");
102   if (Moment *when = unsmob<Moment> (m))
103     return *when;
104   return Moment (0);
105 }
106 
107 bool
is_musical(Grob * me)108 Paper_column::is_musical (Grob *me)
109 {
110   SCM m = get_property (me, "shortest-starter-duration");
111   if (Moment *s = unsmob<Moment> (m))
112     return *s != Moment (0);
113   return false;
114 }
115 
116 bool
is_used(Grob * me)117 Paper_column::is_used (Grob *me)
118 {
119   extract_grob_set (me, "elements", elts);
120   if (elts.size ())
121     return true;
122 
123   extract_grob_set (me, "bounded-by-me", bbm);
124   if (bbm.size ())
125     return true;
126 
127   if (Paper_column::is_breakable (me))
128     return true;
129 
130   if (from_scm<bool> (get_property (me, "used")))
131     return true;
132 
133   if (scm_is_pair (get_property (me, "labels")))
134     return true;
135 
136   return false;
137 }
138 
139 bool
is_breakable(Grob * me)140 Paper_column::is_breakable (Grob *me)
141 {
142   return scm_is_symbol (get_property (me, "line-break-permission"));
143 }
144 
145 Real
minimum_distance(Grob * left,Grob * right)146 Paper_column::minimum_distance (Grob *left, Grob *right)
147 {
148   Drul_array<Grob *> cols (left, right);
149   Drul_array<Skyline> skys = Drul_array<Skyline> (Skyline (RIGHT), Skyline (LEFT));
150 
151   for (LEFT_and_RIGHT (d))
152     {
153       Skyline_pair *sp = unsmob<Skyline_pair> (get_property (cols[d], "horizontal-skylines"));
154       if (sp)
155         skys[d] = (*sp)[-d];
156     }
157 
158   skys[RIGHT].merge (Separation_item::conditional_skyline (right, left));
159 
160   return std::max (0.0, skys[LEFT].distance (skys[RIGHT]));
161 }
162 
163 Interval
break_align_width(Grob * me,SCM align_syms)164 Paper_column::break_align_width (Grob *me, SCM align_syms)
165 {
166   Grob *p = me->get_x_parent ();
167 
168   if (scm_is_symbol (align_syms))
169     align_syms = scm_list_1 (align_syms);
170 
171   if (is_musical (me))
172     {
173       me->programming_error ("tried to get break-align-width of a musical column");
174       return Interval (0, 0) + me->relative_coordinate (p, X_AXIS);
175     }
176 
177   Grob *align = 0;
178   for (; !align && scm_is_pair (align_syms); align_syms = scm_cdr (align_syms))
179     {
180       SCM align_sym = scm_car (align_syms);
181       if (scm_is_eq (align_sym, ly_symbol2scm ("staff-bar"))
182           || scm_is_eq (align_sym, ly_symbol2scm ("break-alignment")))
183         align = Pointer_group_interface::find_grob
184                 (me, ly_symbol2scm ("elements"),
185                  (scm_is_eq (align_sym, ly_symbol2scm ("staff-bar"))
186                   ? Bar_line::non_empty_barline
187                   : has_interface<Break_alignment_interface>));
188       else
189         {
190           extract_grob_set (me, "elements", elts);
191           for (vsize i = 0; i < elts.size (); i++)
192             {
193               if (scm_is_eq (align_sym, get_property (elts[i], "break-align-symbol"))
194                   // TODO SCM: there must be a simpler way to put this.
195                   && !elts[i]->extent (elts[i], X_AXIS).is_empty ())
196                 {
197                   align = elts[i];
198                   break;
199                 }
200             }
201         }
202     }
203 
204   if (!align)
205     return Interval (0, 0) + me->relative_coordinate (p, X_AXIS);
206 
207   return align->extent (p, X_AXIS);
208 }
209 
210 LY_DEFINE (ly_paper_column__break_align_width, "ly:paper-column::break-align-width",
211            2, 0, 0, (SCM col, SCM align_syms),
212            "Determine the extent along the X-axis of a grob used for"
213            " break-alignment organized by column @var{col}. The grob is"
214            " specified by @var{align-syms}, which contains either a"
215            " single @code{break-align-symbol} or a list of such"
216            " symbols.")
217 {
218   LY_ASSERT_SMOB (Grob, col, 1);
219   SCM_ASSERT_TYPE (scm_is_symbol (align_syms) || ly_is_list (align_syms),
220                    align_syms, SCM_ARG2, __FUNCTION__, "symbol or list");
221 
222   Interval ext = Paper_column::break_align_width (unsmob<Grob> (col), align_syms);
223   return to_scm (ext);
224 }
225 
226 /*
227   Loop through elements of a PaperColumn, find all grobs implementing specified
228   interface and return their combined extent.
229 */
230 Interval
get_interface_extent(Grob * column,SCM iface,Axis a)231 Paper_column::get_interface_extent (Grob *column, SCM iface, Axis a)
232 {
233   Interval extent = Interval (0, 0);
234   extract_grob_set (column, "elements", elts);
235 
236   for (vsize i = 0; i < elts.size (); i++)
237     if (elts[i]->internal_has_interface (iface))
238       extent.unite (robust_relative_extent (elts[i], elts[i], a));
239 
240   return extent;
241 }
242 
243 /*
244   Print a:
245   - vertical line,
246   - the rank number,
247   - rank moment,
248   - blue arrow representing ideal distance,
249   - red arrow representing minimum distance
250   to aid debugging.  To turn this on, simply add
251   \override Score.PaperColumn.stencil = #ly:paper-column::print
252   \override Score.NonMusicalPaperColumn.stencil = #ly:paper-column::print
253   to your score.
254   Also, as of 2013-10-16 there's a switch in Frescobaldi that turns this on.
255 */
256 MAKE_DOCUMENTED_SCHEME_CALLBACK (Paper_column, print, 1,
257                                  "Optional stencil for @code{PaperColumn} or"
258                                  "@code{NonMusicalPaperColumn}.\n"
259                                  "Draws the @code{rank number} of each column,"
260                                  " its moment in time, a blue arrow showing the"
261                                  " ideal distance, and a red arrow showing the"
262                                  " minimum distance between columns.");
263 SCM
print(SCM p)264 Paper_column::print (SCM p)
265 {
266   Paper_column *me = unsmob<Paper_column> (p);
267 
268   string r = std::to_string (me->get_rank ());
269 
270   Moment *mom = unsmob<Moment> (get_property (me, "when"));
271   string when = mom ? mom->to_string () : "?/?";
272 
273   Font_metric *musfont = Font_interface::get_default_font (me);
274   SCM properties = Font_interface::text_font_alist_chain (me);
275   SCM scm_mol = Text_interface::interpret_markup (me->layout ()->self_scm (),
276                                                   properties,
277                                                   ly_string2scm (r));
278   SCM when_mol = Text_interface::interpret_markup (me->layout ()->self_scm (),
279                                                    properties,
280                                                    ly_string2scm (when));
281   Stencil t = *unsmob<Stencil> (scm_mol);
282   t.scale (1.2, 1.4);
283   t.add_at_edge (Y_AXIS, DOWN, *unsmob<Stencil> (when_mol), 0.1);
284   t.align_to (X_AXIS, LEFT);
285   // compensate for font serifs and half letter-distance
286   t.translate (Offset (-0.1, 0));
287   t.align_to (Y_AXIS, DOWN);
288 
289   Stencil l = Lookup::filled_box (Box (Interval (0, 0.02),
290                                        Interval (-8, -1)));
291 
292   Real small_pad = 0.15;
293   Real big_pad = 0.35;
294 
295   // number of printed arrows from *both* loops
296   int j = 0;
297 
298   for (SCM s = get_object (me, "ideal-distances");
299        scm_is_pair (s); s = scm_cdr (s))
300     {
301       Spring *sp = unsmob<Spring> (scm_caar (s));
302       if (!unsmob<Grob> (scm_cdar (s))
303           || !unsmob<Grob> (scm_cdar (s))->get_system ())
304         continue;
305 
306       j++;
307 
308       Stencil arrowhead (musfont->find_by_name ("arrowheads.open.01"));
309       // initial scaling; it will also scale with font-size.
310       arrowhead.scale (1, 1.66);
311       Real head_len = arrowhead.extent (X_AXIS).length ();
312 
313       SCM stil = Text_interface::interpret_markup (me->layout ()->self_scm (),
314                                                    properties,
315                                                    ly_string2scm (String_convert::form_string ("%5.2lf", sp->distance ())));
316       Stencil *number_stc = unsmob<Stencil> (stil);
317       number_stc->scale (1, 1.1);
318       Real num_height = number_stc->extent (Y_AXIS).length ();
319       Real num_len = number_stc->extent (X_AXIS).length ();
320       number_stc->align_to (Y_AXIS, DOWN);
321 
322       // arrow's y-coord relative to the top of l stencil:
323       Real y = -2.5;
324       y -= j * (num_height + small_pad + big_pad);
325       // horizontally center number on the arrow, excluding arrowhead.
326       Offset num_off = Offset ((sp->distance () - num_len - head_len) / 2,
327                                y + small_pad);
328 
329       vector<Offset> pts;
330       pts.push_back (Offset (0, y));
331 
332       Offset p2 (sp->distance (), y);
333       pts.push_back (p2);
334 
335       Stencil id_stencil = Lookup::points_to_line_stencil (0.1, pts);
336       id_stencil.add_stencil (arrowhead.translated (p2));
337       id_stencil.add_stencil (number_stc->translated (num_off));
338       // use a lighter shade of blue so it will remain legible on black background.
339       id_stencil = id_stencil.in_color (0.2, 0.4, 1.0);
340       l.add_stencil (id_stencil);
341     }
342 
343   for (SCM s = get_object (me, "minimum-distances");
344        scm_is_pair (s); s = scm_cdr (s))
345     {
346       Real dist = scm_to_double (scm_cdar (s));
347       Grob *other = unsmob<Grob> (scm_caar (s));
348       if (!other || other->get_system () != me->get_system ())
349         continue;
350 
351       j++;
352 
353       Stencil arrowhead (musfont->find_by_name ("arrowheads.open.01"));
354       // initial scaling; it will also scale with font-size.
355       arrowhead.scale (1, 1.66);
356       Real head_len = arrowhead.extent (X_AXIS).length ();
357 
358       SCM stil = Text_interface::interpret_markup (me->layout ()->self_scm (),
359                                                    properties,
360                                                    ly_string2scm (String_convert::form_string ("%5.2lf", dist)));
361       Stencil *number_stc = unsmob<Stencil> (stil);
362       number_stc->scale (1, 1.1);
363       Real num_height = number_stc->extent (Y_AXIS).length ();
364       Real num_len = number_stc->extent (X_AXIS).length ();
365       number_stc->align_to (Y_AXIS, UP);
366 
367       // arrow's y-coord relative to the top of l stencil:
368       Real y = -3;
369       y -= j * (num_height + small_pad + big_pad);
370       // horizontally center number on the arrow, excluding arrowhead.
371       Offset num_off = Offset ((dist - num_len - head_len) / 2,
372                                y - small_pad);
373 
374       vector<Offset> pts;
375       pts.push_back (Offset (0, y));
376 
377       Offset p2 (dist, y);
378       pts.push_back (p2);
379 
380       Stencil id_stencil = Lookup::points_to_line_stencil (0.1, pts);
381       id_stencil.add_stencil (arrowhead.translated (p2));
382       id_stencil.add_stencil (number_stc->translated (num_off));
383       // use a lighter shade of red so it will remain legible on black background.
384       id_stencil = id_stencil.in_color (1.0, 0.25, 0.25);
385       l.add_stencil (id_stencil);
386     }
387   t.add_stencil (l);
388   return t.smobbed_copy ();
389 }
390 
grob_is_live(const Grob * g)391 static bool grob_is_live (const Grob *g)
392 {
393   return g && g->is_live ();
394 }
395 
396 /*
397   This is all too hairy. We use bounded-by-me to make sure that some
398   columns are kept "alive". Unfortunately, when spanners are suicided,
399   this falls apart again, because suicided spanners are still in
400   bounded-by-me
401 
402   THIS IS BROKEN KLUDGE. WE SHOULD INVENT SOMETHING BETTER.
403 */
404 MAKE_SCHEME_CALLBACK (Paper_column, before_line_breaking, 1);
405 SCM
before_line_breaking(SCM grob)406 Paper_column::before_line_breaking (SCM grob)
407 {
408   Grob *me = unsmob<Grob> (grob);
409 
410   if (Grob_array *ga = unsmob<Grob_array> (get_object (me, "bounded-by-me")))
411     ga->filter (grob_is_live);
412 
413   return SCM_UNSPECIFIED;
414 }
415 
416 /* FIXME: This is a hack that we use to identify columns that used to
417    contain note-heads but whose note-heads were moved by one of the ligature
418    engravers. Once the ligature engravers are fixed to behave nicely, this
419    function can be removed.
420 */
421 bool
is_extraneous_column_from_ligature(Grob * me)422 Paper_column::is_extraneous_column_from_ligature (Grob *me)
423 {
424   if (!is_musical (me))
425     return false;
426 
427   // If all the note-heads that I think are my children actually belong
428   // to another column, then I am extraneous.
429   extract_grob_set (me, "elements", elts);
430   bool has_notehead = false;
431   for (vsize i = 0; i < elts.size (); i++)
432     {
433       if (has_interface<Rhythmic_head> (elts[i]))
434         {
435           has_notehead = true;
436           if (dynamic_cast<Item *> (elts[i])->get_column () == me)
437             return false;
438         }
439     }
440   return has_notehead;
441 }
442 
443 ADD_INTERFACE (Paper_column,
444                "@code{Paper_column} objects form the top-most X@tie{}parents"
445                " for items.  There are two types of columns: musical and"
446                " non-musical, to which musical and non-musical objects are"
447                " attached respectively.  The spacing engine determines the"
448                " X@tie{}positions of these objects.\n"
449                "\n"
450                "They are numbered, the first (leftmost) is column@tie{}0."
451                "  Numbering happens before line breaking, and columns are not"
452                " renumbered after line breaking.  Since many columns go"
453                " unused, you should only use the rank field to get ordering"
454                " information.  Two adjacent columns may have non-adjacent"
455                " numbers.",
456 
457                /* properties */
458                "between-cols "
459                "bounded-by-me "
460                "full-measure-extra-space "
461                "grace-spacing "
462                "labels "
463                "line-break-system-details "
464                "line-break-penalty "
465                "line-break-permission "
466                "maybe-loose "
467                "page-break-penalty "
468                "page-break-permission "
469                "page-turn-penalty "
470                "page-turn-permission "
471                "rhythmic-location "
472                "shortest-playing-duration "
473                "shortest-starter-duration "
474                "spacing "
475                "used "
476                "when ");
477