1 /*******************************************************************************
2  * Copyright (c) 2015, 2019 IBM Corporation and others.
3  *
4  * This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License 2.0
6  * which accompanies this distribution, and is available at
7  * https://www.eclipse.org/legal/epl-2.0/
8  *
9  * SPDX-License-Identifier: EPL-2.0
10  *
11  * Contributors:
12  *     IBM Corporation - initial API and implementation
13  *******************************************************************************/
14 package org.eclipse.jface.text.contentassist;
15 
16 import org.eclipse.swt.SWT;
17 import org.eclipse.swt.graphics.Font;
18 import org.eclipse.swt.graphics.FontData;
19 import org.eclipse.swt.graphics.TextStyle;
20 
21 import org.eclipse.jface.viewers.StyledString.Styler;
22 
23 
24 /**
25  * Provides {@link Styler} that applies bold style on the given font.
26  *
27  * @since 3.11
28  */
29 public final class BoldStylerProvider {
30 
31 	private Font fFont;
32 
33 	private Font fBoldFont;
34 
35 	private Styler fBoldStyler;
36 
37 	/**
38 	 * Creates a {@link BoldStylerProvider} instance which uses the given <code>font</code>.
39 	 *
40 	 * @param font the font to use for creating the bold font
41 	 */
BoldStylerProvider(Font font)42 	public BoldStylerProvider(Font font) {
43 		fFont= font;
44 	}
45 
46 	/**
47 	 * Disposes the bold font created for the styler.
48 	 */
dispose()49 	public void dispose() {
50 		if (fBoldFont != null) {
51 			fBoldFont.dispose();
52 			fBoldFont= null;
53 		}
54 	}
55 
56 	/**
57 	 * Returns a {@link Styler} that applies bold style to the given {@link TextStyle}'s font.
58 	 *
59 	 * @return a bold styler
60 	 */
getBoldStyler()61 	public Styler getBoldStyler() {
62 		if (fBoldStyler == null) {
63 			fBoldStyler= new Styler() {
64 				@Override
65 				public void applyStyles(TextStyle textStyle) {
66 					textStyle.font= getBoldFont();
67 				}
68 			};
69 		}
70 		return fBoldStyler;
71 	}
72 
73 	/**
74 	 * Creates (if not already done) and returns the bold font used by the styler to apply the bold
75 	 * style.
76 	 *
77 	 * <p>
78 	 * <strong>Note:</strong> The callers must not cache and re-use the returned font outside the
79 	 * current call.
80 	 * </p>
81 	 *
82 	 * @return the bold font used by the styler
83 	 */
getBoldFont()84 	public Font getBoldFont() {
85 		if (fBoldFont == null) {
86 			FontData[] data= fFont.getFontData();
87 			for (FontData element : data) {
88 				element.setStyle(SWT.BOLD);
89 			}
90 			fBoldFont= new Font(fFont.getDevice(), data);
91 		}
92 		return fBoldFont;
93 	}
94 
95 	/**
96 	 * Returns the font used by the styler to create the bold font.
97 	 *
98 	 * @return the font used for creating the bold font
99 	 */
getFont()100 	public Font getFont() {
101 		return fFont;
102 	}
103 
104 }
105