]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/metadoc/hacking.texi
42bcbee28e88ce4dbb359cf025c21381e948c7ec
[lilypond.git] / Documentation / metadoc / hacking.texi
1 \input texinfo @c -*-texinfo-*-
2 @setfilename internals.info
3 @settitle LilyPond internals
4
5 @node Top, LilyPond internals, (dir), (dir)
6 @top
7
8
9 @menu
10 * LilyPond internals::
11 * Overview::
12 * mudela::                      
13 * Request_engraver::            
14 * Graphic elements::
15 * Score elements::
16 * Items::
17 * Spanners::
18 * Future work::
19 * Coding standards::
20 * Making patches::
21
22 @end menu
23
24 @node LilyPond internals,  , Top, Top
25 @menu
26 * Overview::                      Overview
27 * mudela::                        mudela
28 * Request_engraver::              Request_engraver
29 @end menu
30
31
32 @chapter Help Needed!
33
34 [Call for help]
35
36 [List tasks:
37
38 * Mutopia
39
40 * Doco LilyPond
41
42 * Straightforward extensions
43
44 * GUI editors.
45
46 ]
47
48 @chapter LilyPond internals
49
50
51 This documents some aspects of the internals of GNU LilyPond. Some of
52 this stuff comes from e-mail I wrote, some from e-mail others wrote,
53 some are large comments taken away from the headers. This page may be
54 a little incoherent.  Unfortunately, it is also quite outdated.  A
55 more thorough  and understandable document is in the works.
56
57 You should use @code{doc++} to take a peek at the sources.
58
59 @node Overview, mudela, Top, Top
60 @section Overview
61
62 GNU LilyPond is a "multi-pass" system. The different passes have been
63 created so that they do not depend on each other. In a later stage
64 some parts may be moved into libraries, or seperate programs, or they
65 might be integrated in larger systems.
66
67 @table @samp
68
69 @item Parsing:
70
71 No difficult algorithms. The .ly file is read, and converted to a list
72 of @code{Scores}, which each contain @code{Music} and paper/midi-definitions.
73
74 @item Interpreting music
75
76 The music is walked through in time-order. The iterators which do the
77 walking report Music to Translators which use this information to
78 create elements, either MIDI or "visual" elements. The translators
79 form a hierarchy; the ones for paper output are Engravers, for MIDI
80 Performers.
81
82 The translators swallow Music (mostly atomic gobs called Requests),
83 create elements, broadcast them to other translators on higher or same
84 level in the hierarchy:
85
86 The stem of a voice A is broadcast to the staff which contains A, but
87 not to the stems, beams and noteheads of a different voice (say B) or
88 a different staff. The stem and noteheads of A are coupled, because
89 the the Note_heads_engraver broadcasts its heads, and the Stem_engraver catches
90 these.
91
92 The engraver which agrees to handle a request decides whether to to
93 honor the request, ignore it, or merge it with other requests. Merging
94 of requests is preferably done with other requests done by members of
95 the same voicegroups (beams, brackets, stems). In this way you can put
96 the voices of 2 instruments in a conductor's score so they make chords
97 (the Beam requests of both instruments will be merged).
98
99 @item Prebreaking
100
101 Breakable stuff (eg. clefs and bars) are copied into pre and
102 postbreaks.
103
104 @item Preprocessing
105
106 Some dependencies are resolved, such as the direction of stems, beams,
107 and "horizontal" placement issues (the order of clefs,  keys etc,
108 placement of chords in multi-voice music), 
109
110 @item Break calculation:
111
112 The lines and horizontal positions of the columns are determined.
113
114 @item Breaking
115
116 Through some magical interactions with Line_of_score and Super_elem
117 (check out the source) the "lines" are produced.
118
119 All other spanners can figure across which lines they are spread. If
120 applicable, they break themselves into pieces. After this, each piece
121 (or, if there are no pieces, the original spanner itself) throws out
122 any dependencies which are in the wrong line.
123
124 @item Postprocesing:
125
126 Some items and all spanners need computation after the Paper_column
127 positions are determined. Examples: slurs, vertical positions of
128 staffs.
129
130 @item Output paper
131
132 @end table
133
134 @node mudela, Request_engraver, Overview, Top
135 @section mudela
136
137 Most information is stored in the form of a request.  In music
138 typesetting, the user might want to cram a lot more symbols on the
139 paper than actually fits. To reflect this idea (the user asks more
140 than we can do), the container for this data is called Request.
141
142 In a lot of other formats this would be called an 'Event'
143
144 @table @samp
145 @item @code{Barcheck_req}
146     Checks during music processing if start of this voice element
147     coincides with the start of a measure. Handy to check if you left out
148     some voice elts.
149 @item @code{Note_req}
150     LilyPond has to decide if the ball should be hanging left or
151     right. This influences the horizontal dimensions of a column, and this
152     is why request processing should be done before horizontal spacing.
153     Other voices' frivolities may cause the need for accidentals, so this
154     is also for the to decide. The engraver can decide on positioning based on
155     ottava commands and the appropriate clef.
156 @item @code{Rest_req}
157     Typeset a rest.
158 @item @code{Span_req}
159     This type of request typically results in the creation of a @code{Spanner}
160 @item @code{Beam_req}
161     Start/stop a beam.
162     Engraver has to combine this request with the stem_request, since the
163     number of flags that a stem wants to carry will determine the
164     number of beams.
165 @item @code{Dynamic}
166     Each dynamic is bound to one note (a crescendo spanning multiple
167     notes is thought to be made of two "dynamics": a start and a stop).
168     Dynamic changes can occur in a smaller time than the length of its
169     note, therefore fore each  @code{Dynamic} request carries a time, measured
170     from the start of its note.
171 @end table
172
173 @node Request_engraver, , mudela, Top
174 @section Request_engraver
175
176 In the previous section the idea of Request has been explained, but
177 this only solves one half of the problem. The other half is deciding
178 which requests should be honored, which should merged with other
179 requests, and which should be ignored. Consider this input
180
181 @example 
182
183         \type Staff < % chord
184                 @{ \meter 2/4; [c8 c8] @}
185                 @{\meter 2/4;  [e8 e8] @}
186         >
187  
188 @end example 
189
190 Both the cs and es are part of a staff (they are in the same
191 Voice_group), so they should share meters, but the two [ ] pairs
192 should be merged.
193
194 The judge in this "allocation" problem a set of brokers: the requests
195 are transmitted to so-called engravers which respond if they want to
196 accept a request eg, the @code{Notehead_engraver} will accept
197 @code{Note_req}s, and turn down @code{Slur_req}s. If the Music_iterator
198 cannot find a engraver that wants the request, it is junked (with a
199 warning message).
200
201 After all requests have been either assigned, or junked, the Engraver
202 will process the requests (which usually means creating an @code{Item}
203 or @code{Spanner}). If a @code{Request_engraver} creates something, it
204 tells the enclosing context. If all items/spanners have been created,
205 then each Engraver is notified of any created Score_element, via a
206 broadcasting system.
207
208 @unnumberedsubsec example:
209
210 @example 
211
212         c4
213  
214 @end example 
215
216 produces:
217
218 @example 
219
220         Note_request (duration 1/4)
221         Stem_request (duration 1/4)
222  
223 @end example 
224
225 Note_request will be taken by a @code{Notehead_engraver}, stem_request
226 will be taken by a @code{Stem_beam_engraver}. @code{Notehead_engraver}
227 creates a @code{Notehead}, @code{Stem_beam_engraver} creates a
228 @code{Stem}. Both announce this to the Staff_engraver. Staff_engraver
229 will tell @code{Stem_beam_engraver} about the @code{Notehead}, which
230 will add the @code{Notehead} to the @code{Stem} it just created.
231
232 To decide on merging, several engravers have been grouped. Please
233 check @file{init/engraver.ly}.
234
235
236
237 @node Graphic elements, , , Top 
238 @section Graphic elements
239
240
241 Music notation is composed of a sets of interrelated glyphs.  In
242 Lilypond every glyph usually is represented by one object, a so-called
243 Graphic Object.  The primary relations between graphic objects involve
244 positions:
245
246 @itemize
247 @item consecutive notes are printed left to right, grouped  in a staff
248 @item simultaneous notes are horizontally aligned (internally grouped in
249 a paper column).
250 @item  the staccato mark is horizontally centered on the note it applies
251 to.
252 @end itemize
253
254 The abstract encoding of such relations is done with the concept
255 @dfn{reference point}.  The reference point (in X direction) of the
256 staccato mark is the note it applies to.  The (X) position of the
257 staccato mark is stored relative to the position of the note head.  This
258 means that the staccato will always maintain a fixed offset wrt to the
259 note head, whereever the head is moved to.
260
261 In the same vein, all notes on a staff have their Y positions stored
262 relative to an abstract object called Axis_group_spanner.  If the
263 Axis_group_spanner of one staff is moved, the absolute Y positions of
264 all objects in that spanner change along, in effect causing the staff
265 and all its contents to move as a whole.
266
267 Each graphic object stores a pointer and an relative offset for each
268 direction: one for the X-axis, one for the Y-axis.  For example, the X
269 parent of a Note_head usually is a Note_column.  The X parent of a
270 Note_column usually is either a Collision or a Paper_column. The X
271 parent of a Collision usually is a Paper_column.  If the Collision
272 moves, all Note_heads that have that Collision as parent also move, but
273 the absolute position of the Paper_column does not change.
274
275 To build a graphical score with Graphic_elements, conceptually, one
276 needs to have one Root object (in Lilypond: Line_of_score), and
277 recursively attach objects to the Root.   However, due to the nature
278 of the context selection mechanisms, it turns out to be more
279 advantageous to construct the tree the other way around: first small
280 trees (note heads, barlines etc.) are created, and these are
281 subsequently composed into larger trees, which are finally hung on a
282 Paper_column (in X direction) or Line_of_score (in Y direction). 
283
284 The structure of the X,Y parent relations are determined by the
285 engravers and notation contexts:
286
287 The most important X-axis parent relation depends on the timing: notes
288 that come earlier are attached to Paper_column that will be positioned
289 more to the left.
290
291 The most important Y-axis relation depends on containment of contexts:
292 notes (created in a Thread or Voice context) are put in the staff where
293 the originating context lives in.
294
295 Graphical_axis_groups are special graphic objects, that are designed to
296 function as a parent.  The size of a Graphical_axis_groups group is the
297 union of its children.
298
299 @node Score elements, ,  , Top
300
301 Besides relative positions there are lots of other relations between
302 elements. Lilypond does not contain other specialized relation
303 management (Like the relative positioning code).  In stead, objects can
304 be connected through dependencies, which sets the order in which objects
305 are to be processed.
306
307 Example: the direction of a beamed stem should equal the direction of
308 the beam.  When the stem is a added to the beam, a dependency on the
309 beam is set in the stem: this means that @code{Beam::do_pre_processing
310 ()} (which does various direction related things) will be called before
311 @code{Stem::do_pre_processing ()}.
312
313 The code that manages dependencies resides in the class
314 @code{Score_element}, a derived class of @code{Graphical_element}.  The
315 bulk of the code handles line breaking related issues.
316
317 To sketch the problems with line breaking: suppose a slur spans a line
318 break,
319 @example
320
321 c4(  c'''' c | \break d d )d
322
323 @end example
324 In this case, the slur will appear as two parts, the first part spanning
325 the first three notes (the @code{c}s), the second spanning the last
326 three (the @code{d}s).  Within Lilypond this is modeled as breaking the
327 slur in parts: from the Original slur, two new clones of the old slur
328 are made. Initially both clones depend on the six notes.  After the
329 hairy code in Score_element, Spanner and Item which does substitutions
330 in sets of dependencies, the first clone depends on the first three
331 notes, the second on the last three.
332
333 The major derived classes of Score_element are Item and  Spanner.
334 An item has one horizontal position.  A spanner hangs on two  items.
335
336 @node Items, , , Top
337 @section Items
338
339
340
341 An item is a score element that is associated with only one
342 Paper_column. Examples are note heads, clefs, sup and superscripts, etc.
343 Item is a derived class of Score_element.
344
345 The shape of an item is known before the break calculations, and line
346 spacing depends on the size of items: very wide items need more space
347 than very small ones.
348
349 An additional complication is the behavior of items at linebreaks.  For
350 example, when you do a time signature change, you get only one symbol.
351 If it occurs at a linebreak, the new time signature must be printed both
352 before and after the linebreak.  Other `breakable symbols' such as
353 clefs, and bar lines also exhibit this behavior. 
354
355 if a line of music is broken, the next line usually gets a clef. So in
356 TeX terms, the clef is a postbreak. The same thing happens with meter
357 signs: Normally the meter follows the bar. If a line is broken at that
358 bar, the bar along with the meter stays on the "last" line, but the next
359 line also gets a meter sign after the clef.   To support this,
360 breakable items are generated in the three versions: original
361 (unbroken), left (before line break) and right (after line break).
362 During the line spacing, these versions are used to try how the spacing
363 of a  line works out.
364
365 Once the definitive spacing is determined, dependencies (and various
366 other pointers) are substituted such that all dependencies point at the
367 active items: either they point at the original, or they point at left
368 and right.
369
370 @node Spanners, , , Top
371 @section Spanners
372
373 Spanners are symbols that are of variable shape, eg. Slurs, beams, etc.
374 Spanners is a derived class of Score_element.
375
376 The final shape can only be determined after the line breaking process.
377 All spanners are spanned on two items, called the left and right
378 boundary item.  The X reference point is the left boundary item.
379
380
381 @node Future work, , , Top
382 @section Future work
383
384 There are plans to unify Spanner and Item, so there will no longer be
385 such a clear distinction between the two.  Right now, Score_elements are
386 always either Item or either Spanner.
387
388 Most of the properties of a graphic object are now member variables of
389 the classes involved.  To offer configurability, we want to move these
390 variables to scheme (GUILE) variables, and no longer use C++ code to
391 calculate them, but use Scheme functions.
392
393 @node Coding standards,  , , Top
394
395 @chapter CodingStyle - standards while programming for GNU
396 LilyPond
397
398 Functions and methods do not return errorcodes.
399
400
401 @unnumberedsubsec Languages
402
403 C++ and Python are preferred.  Perl is not.  Python code should use an
404 indent of 8, using TAB characters.
405
406 @unnumberedsubsec Filenames
407
408 Definitions of classes that are only accessed via pointers
409 (*) or references (&) shall not be included as include files.
410
411 filenames
412
413 @example 
414         ".hh"   Include files
415         ".cc"   Implementation files
416         ".icc"  Inline definition files
417         ".tcc"  non inline Template defs
418 @end example 
419
420 in emacs:
421
422 @example 
423         (setq auto-mode-alist
424               (append '(("\\.make$" . makefile-mode)
425                         ("\\.cc$" . c++-mode)
426                         ("\\.icc$" . c++-mode)
427                         ("\\.tcc$" . c++-mode)
428                         ("\\.hh$" . c++-mode)
429                         ("\\.pod$" . text-mode)         
430                         )
431                       auto-mode-alist))
432 @end example 
433
434
435 The class Class_name_abbreviation is coded in @file{class-name-abbr.*}
436
437 @unnumberedsubsec Indentation
438
439 Standard GNU coding style is used.   In emacs:
440
441 @example 
442         (add-hook 'c++-mode-hook
443                   '(lambda() (c-set-style "gnu")
444                      )
445                   )
446 @end example 
447
448 If you like using font-lock, you can also add this to your @file{.emacs}:
449
450 @example 
451         (setq font-lock-maximum-decoration t)
452         (setq c++-font-lock-keywords-3 
453               (append
454                c++-font-lock-keywords-3
455                '(("\\b\\([a-zA-Z_]+_\\)\\b" 1 font-lock-variable-name-face)
456                ("\\b\\([A-Z]+[a-z_]+\\)\\b" 1 font-lock-type-face))
457                ))
458 @end example 
459
460 @unnumberedsubsec Classes and Types
461
462 @example 
463         This_is_a_class
464 @end example 
465
466 @unnumberedsubsec Members
467
468 @example 
469         Class::member ()
470         Type Class::member_type_
471         Type Class::member_type ()
472 @end example 
473
474 the @code{type} is a Hungarian notation postfix for @code{Type}. See below
475
476 @unnumberedsubsec Macros
477
478 Macros should be written completely in uppercase
479
480 The code should not be compilable if proper macro declarations are not
481 included. 
482
483 Don't laugh. It took us a whole evening/night to figure out one of
484 these bugs, because we had a macro that looked like
485 @code{DECLARE_VIRTUAL_FUNCTIONS ()}. 
486
487 @unnumberedsubsec Broken code
488
489 Broken code (hardwired dependencies, hardwired constants, slow
490 algorithms and obvious limitations) should be marked as such: either
491 with a verbose TODO, or with a short "ugh" comment.
492
493 @unnumberedsubsec Comments
494
495 The source is commented in the DOC++ style.  Check out doc++ at
496 @uref{http://www.zib.de/Visual/software/doc++/index.html}
497
498 @example 
499
500         /*
501                 C style comments for multiline comments.
502                 They come before the thing to document.
503                 [...]
504         */
505
506         /**
507                 short description.
508                 Long class documentation.
509                 (Hungarian postfix)
510
511                 TODO Fix boring_member ()
512         */
513         class Class @{
514                 /**
515                   short description.
516                   long description
517                 */
518
519                 Data data_member_;
520
521                 /**
522                         short memo. long doco of member ()
523                         @@param description of arguments
524                         @@return Rettype
525                 */
526                 Rettype member (Argtype);
527
528                 /// memo only
529                 boring_member () @{
530                         data_member_ = 121; // ugh
531                 @}
532         @};
533  
534 @end example 
535
536         
537 Unfortunately most of the code isn't really documented that good.
538
539 @unnumberedsubsec Members (2)
540
541 Standard methods:
542
543 @example 
544
545         ///check that *this satisfies its invariants, abort if not.
546         void OK () const
547
548         /// print *this (and substructures) to debugging log
549         void print () const
550
551         /**
552         protected member. Usually invoked by non-virtual XXXX ()
553         */
554         virtual do_XXXX ()
555
556         /**add some data to *this.
557         Presence of these methods usually imply that it is not feasible to this
558         via  a constructor
559         */
560         add (..)
561
562         /// replace some data of *this
563         set (..)
564  
565 @end example 
566
567 @unnumberedsubsec Constructor
568
569 Every class should have a default constructor.  
570
571 Don't use non-default constructors if this can be avoided:
572
573 @example 
574
575         Foo f(1)
576  
577 @end example 
578
579 is less readable than
580
581 @example 
582
583         Foo f;
584         f.x = 1
585  
586 @end example 
587
588 or 
589
590 @example 
591
592         Foo f(Foo_convert::int_to_foo (1))
593  
594 @end example 
595
596 @unnumberedsec Hungarian notation naming convention
597
598 Proposed is a naming convention derived from the so-called
599 @emph{Hungarian Notation}.  Macros, @code{enum}s and @code{const}s are all
600 uppercase, with the parts of the names separated by underscores.
601
602 The hungarian notation  is to be used when variables are not declared
603 near usage (mostly in member variables and functions).
604
605 @unnumberedsubsec Types
606
607 @table @samp
608 @item @code{byte}
609     unsigned char. (The postfix _by is ambiguous)
610 @item @code{b}
611     bool
612 @item @code{bi}
613     bit
614 @item @code{ch}
615     char
616 @item @code{f}
617     float
618 @item @code{i}
619     signed integer
620 @item @code{str}
621     string class
622 @item @code{sz}
623     Zero terminated c string
624 @item @code{u}
625     unsigned integer
626 @end table
627
628 @unnumberedsubsec User defined types
629
630 @example 
631
632         /** Slur blah. blah.
633         (slur)
634         */
635         class Slur @{@};
636         Slur* slur_p = new Slur;
637  
638 @end example 
639
640 @unnumberedsubsec Modifiers
641
642 The following types modify the meaning of the prefix. 
643 These are preceded by the prefixes:
644
645 @table @samp
646 @item @code{a}
647     array
648 @item @code{array}
649     user built array.
650 @item @code{c}
651     const. Note that the proper order is @code{Type const}
652     i.s.o. @code{const Type}
653 @item @code{C}
654     A const pointer. This would be equivalent to @code{_c_l}, but since any
655     "const" pointer has to be a link (you can't delete a const pointer),
656     it is superfluous.
657 @item @code{l}
658     temporary pointer to object (link)
659 @item @code{p}
660     pointer to newed object
661 @item @code{r}
662     reference
663 @end table
664
665 @unnumberedsubsec Adjective
666
667 Adjectives such as global and static should be spelled out in full.
668 They come before the noun that they refer to, just as in normal english.
669
670 @example 
671
672 foo_global_i: a global variable of type int commonly called "foo".
673  
674 @end example 
675
676 static class members do not need the static_ prefix in the name (the
677 Class::var notation usually makes it clear that it is static)
678
679 @table @samp
680 @item @code{loop_i}
681     Variable loop: an integer
682 @item @code{u}
683     Temporary variable: an unsigned integer
684 @item @code{test_ch}
685     Variable test: a character
686 @item @code{first_name_str}
687     Variable first_name: a String class object
688 @item @code{last_name_ch_a}
689     Variable last_name: a @code{char} array
690 @item @code{foo_i_p}
691     Variable foo: an @code{Int*} that you must delete
692 @item @code{bar_i_l}
693     Variable bar: an @code{Int*} that you must not delete
694 @end table
695
696 Generally default arguments are taboo, except for nil pointers.
697
698 The naming convention can be quite conveniently memorised, by
699 expressing the type in english, and abbreviating it
700
701 @example 
702
703         static Array<int*> foo
704  
705 @end example 
706
707 @code{foo} can be described as "the static int-pointer user-array", so you get
708
709 @example 
710
711         foo_static_l_arr
712  
713 @end example 
714
715
716 @unnumberedsec Miscellaneous
717     
718 For some tasks, some scripts are supplied, notably creating patches, a
719 mirror of the website, generating the header to put over cc and hh
720 files, doing a release.
721
722 Use them.
723
724 @node Making patches,  , , Top
725
726
727 @unnumberedsec name
728     
729
730 PATCHES - track and distribute your code changes
731
732 This page documents how to distribute your changes to GNU lilypond
733     
734 We would like to have unified context diffs with full pathnames.  A
735 script automating supplied with Lily.
736
737 Distributing a change normally goes like this:
738
739 @itemize @bullet
740 @item make your fix/add your code 
741 @item Add changes to CHANGES, and add yourself to Documentation/topdocs/AUTHORS.texi
742 @item generate a patch, 
743 @item e-mail your patch to one of the mailing lists
744     gnu-music-discuss@@gnu.org or bug-gnu-music@@gnu.org
745 @end itemize
746
747 Please do not send entire files, even if the patch is bigger than the
748 original.  A patch makes it clear what is changed, and it won't
749 overwrite previous (not yet released) changes.
750
751 @unnumberedsec Generating a patch
752
753 Simple version: run
754
755 @example
756         make -C lilypond-x.y.z/ distclean
757         make -C lilypond-x.y.z.NEW/ distclean
758         diff -urN lilypond-x.y.z/ lilypond-x.y.z.NEW/
759 @end example
760
761 Complicated (but automated) version:
762
763 In @file{VERSION}, set MY_PATCH_LEVEL:
764
765 @example 
766
767     VERSION:
768         ...
769         MY_PATCH_LEVEL=jcn1
770  
771 @end example 
772
773 In @file{CHANGES}, enter a summary of changes:
774
775 @example 
776         pl 0.1.73.jcn1
777                 - added PATCHES.texi
778 @end example 
779
780 Then, from the top of Lily's source tree, type
781
782 @example 
783     make release
784 @end example 
785
786 These handy python scripts assume a directory structure which looks
787 like:
788
789 @example 
790
791     lilypond -> lilypond-x.y.z   # symlink to development directory
792     lilypond-x.y.z/              # current development
793     patches/                     # patches between different releases
794     releases/                    # .tar.gz releases
795
796 @end example 
797
798 (Some scripts also assume this lives in  @file{$HOME/usr/src}).
799
800         
801 @unnumberedsec Applying patches
802     
803
804 If you're following LilyPond development regularly, you probably want to
805 download just the patch for each subsequent release.
806 After downloading the patch (into the patches directory, of course), simply 
807 apply it:
808
809 @example 
810
811     gzip -dc ../patches/lilypond-0.1.74.diff.gz | patch -p1 -E
812  
813 @end example 
814
815 and don't forget to make automatically generated files:
816
817 @example 
818
819     autoconf footnote(patches don't include automatically generated files, 
820     i.e. file(configure) and files generated by file(configure).)
821
822     configure
823  
824 @end example 
825     
826
827 @bye
828
829