1 #include <algorithm>
2 #include <map>
3 using namespace std;
4 
5 #include "keywords.h"
6 
7 #include "libannotate/Text.h"
8 #include "libdisplay/libdisplay.h"
9 
10 static int
findOverlap(multimap<int,Text * > & textMap,Text * text)11 findOverlap(multimap<int, Text *> &textMap, Text *text)
12 {
13     int totalOverlap = 0;
14     multimap<int, Text *>::iterator textIterator;
15     for (textIterator = textMap.begin();
16 	 textIterator != textMap.end();
17 	 textIterator++)
18     {
19 	Text *t = textIterator->second;
20 	if (t != text) totalOverlap += text->Overlap(t);
21     }
22     return(totalOverlap);
23 }
24 
25 void
arrangeMarkers(multimap<double,Annotation * > & annotationMap,DisplayBase * display)26 arrangeMarkers(multimap<double, Annotation *> &annotationMap,
27 	       DisplayBase *display)
28 {
29     if (annotationMap.empty()) return;
30 
31     // This will hold a list of text strings, sorted by x coordinate
32     multimap<int, Text *> textMap;
33 
34     multimap<double, Annotation *>::iterator annotationIterator;
35     for (annotationIterator = annotationMap.begin();
36 	 annotationIterator != annotationMap.end();
37 	 annotationIterator++)
38     {
39 	Text *t = dynamic_cast<Text *> (annotationIterator->second);
40 	if (t != NULL)
41 	{
42 	    t->ComputeBoundingBox(display);
43 	    textMap.insert(pair<const int, Text *>(t->X(), t));
44 	}
45     }
46 
47     const int align[4] = { RIGHT, LEFT, ABOVE, BELOW };
48 
49     for (int i = 0; i < 2; i++)
50     {
51 	multimap<int, Text *>::iterator textIterator;
52 	for (textIterator = textMap.begin();
53 	     textIterator != textMap.end();
54 	     textIterator++)
55 	{
56 	    Text *t = textIterator->second;
57 
58 	    if (t->FixedAlign()) continue;
59 
60 	    int totalOverlap = 0;
61 	    int minOverlap = 0;
62 	    int alignIndex = 0;
63 
64 	    // Choose the alignment which yields the minimum overlap for
65 	    // this marker
66 	    for (int i = 0; i < 4; i++)
67 	    {
68 		if (i == 0 || totalOverlap)
69 		{
70 		    t->Align(align[i]);
71 
72 		    totalOverlap = findOverlap(textMap, t);
73 		    totalOverlap += t->Overhang(display->Width(),
74 						display->Height());
75 		    if (i == 0 || totalOverlap < minOverlap)
76 		    {
77 			minOverlap = totalOverlap;
78 			alignIndex = i;
79 		    }
80 		}
81 	    }
82 	    t->Align(align[alignIndex]);
83 	}
84     }
85 }
86