source: josm/trunk/src/org/openstreetmap/josm/tools/WindowGeometry.java@ 8395

Last change on this file since 8395 was 8394, checked in by Don-vip, 9 years ago
  • global use of String.isEmpty()
  • Correctness - Method throws alternative exception from catch block without history
  • Property svn:eol-style set to native
File size: 17.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Component;
7import java.awt.Dimension;
8import java.awt.GraphicsConfiguration;
9import java.awt.GraphicsDevice;
10import java.awt.GraphicsEnvironment;
11import java.awt.Insets;
12import java.awt.Point;
13import java.awt.Rectangle;
14import java.awt.Toolkit;
15import java.awt.Window;
16import java.util.regex.Matcher;
17import java.util.regex.Pattern;
18
19import javax.swing.JComponent;
20
21import org.openstreetmap.josm.Main;
22
23/**
24 * This is a helper class for persisting the geometry of a JOSM window to the preference store
25 * and for restoring it from the preference store.
26 *
27 */
28public class WindowGeometry {
29
30 /**
31 * Replies a window geometry object for a window with a specific size which is
32 * centered on screen, where main window is
33 *
34 * @param extent the size
35 * @return the geometry object
36 */
37 public static WindowGeometry centerOnScreen(Dimension extent) {
38 return centerOnScreen(extent, "gui.geometry");
39 }
40
41 /**
42 * Replies a window geometry object for a window with a specific size which is
43 * centered on screen where the corresponding window is.
44 *
45 * @param extent the size
46 * @param preferenceKey the key to get window size and position from, null value format
47 * for whole virtual screen
48 * @return the geometry object
49 */
50 public static WindowGeometry centerOnScreen(Dimension extent, String preferenceKey) {
51 Rectangle size = preferenceKey != null ? getScreenInfo(preferenceKey)
52 : getFullScreenInfo();
53 Point topLeft = new Point(
54 size.x + Math.max(0, (size.width - extent.width) /2),
55 size.y + Math.max(0, (size.height - extent.height) /2)
56 );
57 return new WindowGeometry(topLeft, extent);
58 }
59
60 /**
61 * Replies a window geometry object for a window with a specific size which is centered
62 * relative to the parent window of a reference component.
63 *
64 * @param reference the reference component.
65 * @param extent the size
66 * @return the geometry object
67 */
68 public static WindowGeometry centerInWindow(Component reference, Dimension extent) {
69 Window parentWindow = null;
70 while(reference != null && ! (reference instanceof Window) ) {
71 reference = reference.getParent();
72 }
73 if (reference == null)
74 return new WindowGeometry(new Point(0,0), extent);
75 parentWindow = (Window)reference;
76 Point topLeft = new Point(
77 Math.max(0, (parentWindow.getSize().width - extent.width) /2),
78 Math.max(0, (parentWindow.getSize().height - extent.height) /2)
79 );
80 topLeft.x += parentWindow.getLocation().x;
81 topLeft.y += parentWindow.getLocation().y;
82 return new WindowGeometry(topLeft, extent);
83 }
84
85 /**
86 * Exception thrown by the WindowGeometry class if something goes wrong
87 */
88 public static class WindowGeometryException extends Exception {
89 public WindowGeometryException(String message, Throwable cause) {
90 super(message, cause);
91 }
92
93 public WindowGeometryException(String message) {
94 super(message);
95 }
96 }
97
98 /** the top left point */
99 private Point topLeft;
100 /** the size */
101 private Dimension extent;
102
103 /**
104 * Creates a window geometry from a position and dimension
105 *
106 * @param topLeft the top left point
107 * @param extent the extent
108 */
109 public WindowGeometry(Point topLeft, Dimension extent) {
110 this.topLeft = topLeft;
111 this.extent = extent;
112 }
113
114 /**
115 * Creates a window geometry from a rectangle
116 *
117 * @param rect the position
118 */
119 public WindowGeometry(Rectangle rect) {
120 this.topLeft = rect.getLocation();
121 this.extent = rect.getSize();
122 }
123
124 /**
125 * Creates a window geometry from the position and the size of a window.
126 *
127 * @param window the window
128 */
129 public WindowGeometry(Window window) {
130 this(window.getLocationOnScreen(), window.getSize());
131 }
132
133 /**
134 * Fixes a window geometry to shift to the correct screen.
135 *
136 * @param window the window
137 */
138 public void fixScreen(Window window) {
139 Rectangle oldScreen = getScreenInfo(getRectangle());
140 Rectangle newScreen = getScreenInfo(new Rectangle(window.getLocationOnScreen(), window.getSize()));
141 if(oldScreen.x != newScreen.x) {
142 this.topLeft.x += newScreen.x - oldScreen.x;
143 }
144 if(oldScreen.y != newScreen.y) {
145 this.topLeft.y += newScreen.y - oldScreen.y;
146 }
147 }
148
149 protected int parseField(String preferenceKey, String preferenceValue, String field) throws WindowGeometryException {
150 String v = "";
151 try {
152 Pattern p = Pattern.compile(field + "=(-?\\d+)",Pattern.CASE_INSENSITIVE);
153 Matcher m = p.matcher(preferenceValue);
154 if (!m.find())
155 throw new WindowGeometryException(
156 tr("Preference with key ''{0}'' does not include ''{1}''. Cannot restore window geometry from preferences.",
157 preferenceKey, field));
158 v = m.group(1);
159 return Integer.parseInt(v);
160 } catch(WindowGeometryException e) {
161 throw e;
162 } catch(NumberFormatException e) {
163 throw new WindowGeometryException(
164 tr("Preference with key ''{0}'' does not provide an int value for ''{1}''. Got {2}. Cannot restore window geometry from preferences.",
165 preferenceKey, field, v), e);
166 } catch(Exception e) {
167 throw new WindowGeometryException(
168 tr("Failed to parse field ''{1}'' in preference with key ''{0}''. Exception was: {2}. Cannot restore window geometry from preferences.",
169 preferenceKey, field, e.toString()), e);
170 }
171 }
172
173 protected final void initFromPreferences(String preferenceKey) throws WindowGeometryException {
174 String value = Main.pref.get(preferenceKey);
175 if (value == null || value.isEmpty())
176 throw new WindowGeometryException(
177 tr("Preference with key ''{0}'' does not exist. Cannot restore window geometry from preferences.", preferenceKey));
178 topLeft = new Point();
179 extent = new Dimension();
180 topLeft.x = parseField(preferenceKey, value, "x");
181 topLeft.y = parseField(preferenceKey, value, "y");
182 extent.width = parseField(preferenceKey, value, "width");
183 extent.height = parseField(preferenceKey, value, "height");
184 }
185
186 protected final void initFromWindowGeometry(WindowGeometry other) {
187 this.topLeft = other.topLeft;
188 this.extent = other.extent;
189 }
190
191 public static WindowGeometry mainWindow(String preferenceKey, String arg, boolean maximize) {
192 Rectangle screenDimension = getScreenInfo("gui.geometry");
193 if (arg != null) {
194 final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(arg);
195 if (m.matches()) {
196 int w = Integer.parseInt(m.group(1));
197 int h = Integer.parseInt(m.group(2));
198 int x = screenDimension.x, y = screenDimension.y;
199 if (m.group(3) != null) {
200 x = Integer.parseInt(m.group(5));
201 y = Integer.parseInt(m.group(7));
202 if ("-".equals(m.group(4))) {
203 x = screenDimension.x + screenDimension.width - x - w;
204 }
205 if ("-".equals(m.group(6))) {
206 y = screenDimension.y + screenDimension.height - y - h;
207 }
208 }
209 return new WindowGeometry(new Point(x,y), new Dimension(w,h));
210 } else {
211 Main.warn(tr("Ignoring malformed geometry: {0}", arg));
212 }
213 }
214 WindowGeometry def;
215 if(maximize) {
216 def = new WindowGeometry(screenDimension);
217 } else {
218 Point p = screenDimension.getLocation();
219 p.x += (screenDimension.width-1000)/2;
220 p.y += (screenDimension.height-740)/2;
221 def = new WindowGeometry(p, new Dimension(1000, 740));
222 }
223 return new WindowGeometry(preferenceKey, def);
224 }
225
226 /**
227 * Creates a window geometry from the values kept in the preference store under the
228 * key <code>preferenceKey</code>
229 *
230 * @param preferenceKey the preference key
231 * @throws WindowGeometryException if no such key exist or if the preference value has
232 * an illegal format
233 */
234 public WindowGeometry(String preferenceKey) throws WindowGeometryException {
235 initFromPreferences(preferenceKey);
236 }
237
238 /**
239 * Creates a window geometry from the values kept in the preference store under the
240 * key <code>preferenceKey</code>. Falls back to the <code>defaultGeometry</code> if
241 * something goes wrong.
242 *
243 * @param preferenceKey the preference key
244 * @param defaultGeometry the default geometry
245 *
246 */
247 public WindowGeometry(String preferenceKey, WindowGeometry defaultGeometry) {
248 try {
249 initFromPreferences(preferenceKey);
250 } catch(WindowGeometryException e) {
251 initFromWindowGeometry(defaultGeometry);
252 }
253 }
254
255 /**
256 * Remembers a window geometry under a specific preference key
257 *
258 * @param preferenceKey the preference key
259 */
260 public void remember(String preferenceKey) {
261 StringBuilder value = new StringBuilder();
262 value.append("x=").append(topLeft.x).append(",y=").append(topLeft.y)
263 .append(",width=").append(extent.width).append(",height=").append(extent.height);
264 Main.pref.put(preferenceKey, value.toString());
265 }
266
267 /**
268 * Replies the top left point for the geometry
269 *
270 * @return the top left point for the geometry
271 */
272 public Point getTopLeft() {
273 return topLeft;
274 }
275
276 /**
277 * Replies the size specified by the geometry
278 *
279 * @return the size specified by the geometry
280 */
281 public Dimension getSize() {
282 return extent;
283 }
284
285 /**
286 * Replies the size and position specified by the geometry
287 *
288 * @return the size and position specified by the geometry
289 */
290 private Rectangle getRectangle() {
291 return new Rectangle(topLeft, extent);
292 }
293
294 /**
295 * Applies this geometry to a window. Makes sure that the window is not
296 * placed outside of the coordinate range of all available screens.
297 *
298 * @param window the window
299 */
300 public void applySafe(Window window) {
301 Point p = new Point(topLeft);
302 Dimension size = new Dimension(extent);
303
304 Rectangle virtualBounds = getVirtualScreenBounds();
305
306 // Ensure window fit on screen
307
308 if (p.x < virtualBounds.x) {
309 p.x = virtualBounds.x;
310 } else if (p.x > virtualBounds.x + virtualBounds.width - size.width) {
311 p.x = virtualBounds.x + virtualBounds.width - size.width;
312 }
313
314 if (p.y < virtualBounds.y) {
315 p.y = virtualBounds.y;
316 } else if (p.y > virtualBounds.y + virtualBounds.height - size.height) {
317 p.y = virtualBounds.y + virtualBounds.height - size.height;
318 }
319
320 int deltax = (p.x + size.width) - (virtualBounds.x + virtualBounds.width);
321 if (deltax > 0) {
322 size.width -= deltax;
323 }
324
325 int deltay = (p.y + size.height) - (virtualBounds.y + virtualBounds.height);
326 if (deltay > 0) {
327 size.height -= deltay;
328 }
329
330 // Ensure window does not hide taskbar
331
332 Rectangle maxbounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
333
334 if (!isBugInMaximumWindowBounds(maxbounds)) {
335 deltax = size.width - maxbounds.width;
336 if (deltax > 0) {
337 size.width -= deltax;
338 }
339
340 deltay = size.height - maxbounds.height;
341 if (deltay > 0) {
342 size.height -= deltay;
343 }
344 }
345 window.setLocation(p);
346 window.setSize(size);
347 }
348
349 /**
350 * Determines if the bug affecting getMaximumWindowBounds() occured.
351 *
352 * @param maxbounds result of getMaximumWindowBounds()
353 * @return {@code true} if the bug happened, {@code false otherwise}
354 *
355 * @see <a href="https://josm.openstreetmap.de/ticket/9699">JOSM-9699</a>
356 * @see <a href="https://bugs.launchpad.net/ubuntu/+source/openjdk-7/+bug/1171563">Ubuntu-1171563</a>
357 * @see <a href="http://icedtea.classpath.org/bugzilla/show_bug.cgi?id=1669">IcedTea-1669</a>
358 * @see <a href="https://bugs.openjdk.java.net/browse/JI-9010334">JI-9010334</a>
359 */
360 protected static boolean isBugInMaximumWindowBounds(Rectangle maxbounds) {
361 return maxbounds.width <= 0 || maxbounds.height <= 0;
362 }
363
364 /**
365 * Computes the virtual bounds of graphics environment, as an union of all screen bounds.
366 * @return The virtual bounds of graphics environment, as an union of all screen bounds.
367 * @since 6522
368 */
369 public static Rectangle getVirtualScreenBounds() {
370 Rectangle virtualBounds = new Rectangle();
371 GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
372 for (GraphicsDevice gd : ge.getScreenDevices()) {
373 if (gd.getType() == GraphicsDevice.TYPE_RASTER_SCREEN) {
374 virtualBounds = virtualBounds.union(gd.getDefaultConfiguration().getBounds());
375 }
376 }
377 return virtualBounds;
378 }
379
380 /**
381 * Computes the maximum dimension for a component to fit in screen displaying {@code component}.
382 * @param component The component to get current screen info from. Must not be {@code null}
383 * @return the maximum dimension for a component to fit in current screen
384 * @throws IllegalArgumentException if {@code component} is null
385 * @since 7463
386 */
387 public static Dimension getMaxDimensionOnScreen(JComponent component) {
388 CheckParameterUtil.ensureParameterNotNull(component, "component");
389 // Compute max dimension of current screen
390 Dimension result = new Dimension();
391 GraphicsConfiguration gc = component.getGraphicsConfiguration();
392 if (gc == null && Main.parent != null) {
393 gc = Main.parent.getGraphicsConfiguration();
394 }
395 if (gc != null) {
396 // Max displayable dimension (max screen dimension - insets)
397 Rectangle bounds = gc.getBounds();
398 Insets insets = component.getToolkit().getScreenInsets(gc);
399 result.width = bounds.width - insets.left - insets.right;
400 result.height = bounds.height - insets.top - insets.bottom;
401 }
402 return result;
403 }
404
405 /**
406 * Find the size and position of the screen for given coordinates. Use first screen,
407 * when no coordinates are stored or null is passed.
408 *
409 * @param preferenceKey the key to get size and position from
410 * @return bounds of the screen
411 */
412 public static Rectangle getScreenInfo(String preferenceKey) {
413 Rectangle g = new WindowGeometry(preferenceKey,
414 /* default: something on screen 1 */
415 new WindowGeometry(new Point(0,0), new Dimension(10,10))).getRectangle();
416 return getScreenInfo(g);
417 }
418
419 /**
420 * Find the size and position of the screen for given coordinates. Use first screen,
421 * when no coordinates are stored or null is passed.
422 *
423 * @param g coordinates to check
424 * @return bounds of the screen
425 */
426 private static Rectangle getScreenInfo(Rectangle g) {
427 GraphicsEnvironment ge = GraphicsEnvironment
428 .getLocalGraphicsEnvironment();
429 GraphicsDevice[] gs = ge.getScreenDevices();
430 int intersect = 0;
431 Rectangle bounds = null;
432 for (GraphicsDevice gd : gs) {
433 if (gd.getType() == GraphicsDevice.TYPE_RASTER_SCREEN) {
434 Rectangle b = gd.getDefaultConfiguration().getBounds();
435 if (b.height > 0 && b.width / b.height >= 3) /* multiscreen with wrong definition */ {
436 b.width /= 2;
437 Rectangle is = b.intersection(g);
438 int s = is.width * is.height;
439 if (bounds == null || intersect < s) {
440 intersect = s;
441 bounds = b;
442 }
443 b = new Rectangle(b);
444 b.x += b.width;
445 is = b.intersection(g);
446 s = is.width * is.height;
447 if (bounds == null || intersect < s) {
448 intersect = s;
449 bounds = b;
450 }
451 } else {
452 Rectangle is = b.intersection(g);
453 int s = is.width * is.height;
454 if (bounds == null || intersect < s) {
455 intersect = s;
456 bounds = b;
457 }
458 }
459 }
460 }
461 return bounds;
462 }
463
464 /**
465 * Find the size of the full virtual screen.
466 * @return size of the full virtual screen
467 */
468 public static Rectangle getFullScreenInfo() {
469 return new Rectangle(new Point(0,0), Toolkit.getDefaultToolkit().getScreenSize());
470 }
471
472 @Override
473 public String toString() {
474 return "WindowGeometry{topLeft="+topLeft+",extent="+extent+"}";
475 }
476}
Note: See TracBrowser for help on using the repository browser.